text stringlengths 0 444 |
|---|
==== |
Don't use `||=` to initialize boolean variables. |
(Consider what would happen if the current value happened to be `false`.) |
[source,ruby] |
---- |
# bad - would set enabled to true even if it was false |
enabled ||= true |
# good |
enabled = true if enabled.nil? |
---- |
==== |
=== Existence Check Shorthand [[double-amper-preprocess]] |
Use `&&=` to preprocess variables that may or may not exist. |
Using `&&=` will change the value only if it exists, removing the need to check its existence with `if`. |
[source,ruby] |
---- |
# bad |
if something |
something = something.downcase |
end |
# bad |
something = something ? something.downcase : nil |
# ok |
something = something.downcase if something |
# good |
something = something && something.downcase |
# better |
something &&= something.downcase |
---- |
=== Identity Comparison [[identity-comparison]] |
Prefer `equal?` over `==` when comparing `object_id`. `Object#equal?` is provided to compare objects for identity, and in contrast `Object#==` is provided for the purpose of doing value comparison. |
[source,ruby] |
---- |
# bad |
foo.object_id == bar.object_id |
# good |
foo.equal?(bar) |
---- |
Similarly, prefer using `Hash#compare_by_identity` than using `object_id` for keys: |
[source,ruby] |
---- |
# bad |
hash = {} |
hash[foo.object_id] = :bar |
if hash.key?(baz.object_id) # ... |
# good |
hash = {}.compare_by_identity |
hash[foo] = :bar |
if hash.key?(baz) # ... |
---- |
Note that `Set` also has `Set#compare_by_identity` available. |
=== Explicit Use of the Case Equality Operator [[no-case-equality]] |
Avoid explicit use of the case equality operator `===`. |
As its name implies it is meant to be used implicitly by `case` expressions and outside of them it yields some pretty confusing code. |
[source,ruby] |
---- |
# bad |
Array === something |
(1..100) === 7 |
/something/ === some_string |
# good |
something.is_a?(Array) |
(1..100).include?(7) |
some_string.match?(/something/) |
---- |
NOTE: With direct subclasses of `BasicObject`, using `is_a?` is not an option since `BasicObject` doesn't provide that method (it's defined in `Object`). In those |
rare cases it's OK to use `===`. |
=== `is_a?` vs `kind_of?` [[is-a-vs-kind-of]] |
Prefer `is_a?` over `kind_of?`. The two methods are synonyms, but `is_a?` is the more commonly used name in the wild. |
[source,ruby] |
---- |
# bad |
something.kind_of?(Array) |
# good |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.