text
stringlengths
0
444
something.is_a?(Array)
----
=== `is_a?` vs `instance_of?` [[is-a-vs-instance-of]]
Prefer `is_a?` over `instance_of?`.
While the two methods are similar, `is_a?` will consider the whole inheritance
chain (superclasses and included modules), which is what you normally would want
to do. `instance_of?`, on the other hand, only returns `true` if an object is an
instance of that exact class you're checking for, not a subclass.
[source,ruby]
----
# bad
something.instance_of?(Array)
# good
something.is_a?(Array)
----
=== `instance_of?` vs class comparison [[instance-of-vs-class-comparison]]
Use `Object#instance_of?` instead of class comparison for equality.
[source,ruby]
----
# bad
var.class == Date
var.class.equal?(Date)
var.class.eql?(Date)
var.class.name == 'Date'
# good
var.instance_of?(Date)
----
=== `==` vs `eql?` [[eql]]
Do not use `eql?` when using `==` will do.
The stricter comparison semantics provided by `eql?` are rarely needed in practice.
[source,ruby]
----
# bad - eql? is the same as == for strings
'ruby'.eql? some_str
# good
'ruby' == some_str
1.0.eql? x # eql? makes sense here if want to differentiate between Integer and Float 1
----
== Blocks, Procs & Lambdas
=== Proc Application Shorthand [[single-action-blocks]]
Use the Proc call shorthand when the called method is the only operation of a block.
[source,ruby]
----
# bad
names.map { |name| name.upcase }
# good
names.map(&:upcase)
----
=== Single-line Blocks Delimiters [[single-line-blocks]]
Prefer `{...}` over `do...end` for single-line blocks.
Avoid using `{...}` for multi-line blocks (multi-line chaining is always ugly).
Always use `do...end` for "control flow" and "method definitions" (e.g. in Rakefiles and certain DSLs).
Avoid `do...end` when chaining.
[source,ruby]
----
names = %w[Bozhidar Filipp Sarah]
# bad
names.each do |name|
puts name
end
# good
names.each { |name| puts name }
# bad
names.select do |name|
name.start_with?('S')
end.map { |name| name.upcase }
# good
names.select { |name| name.start_with?('S') }.map(&:upcase)
----
Some will argue that multi-line chaining would look OK with the use of {...}, but they should ask themselves - is this code really readable and can the blocks' contents be extracted into nifty methods?
=== Explicit Block Argument [[block-argument]]
Consider using explicit block argument to avoid writing block literal that just passes its arguments to another block.