text
stringlengths 0
444
|
|---|
# good
|
def do_something(params = {})
|
unless params[:when] == :later
|
output(options[:message])
|
end
|
end
|
end
|
----
|
=== Safe Assignment in Condition [[safe-assignment-in-condition]]
|
Don't use the return value of `=` (an assignment) in conditional expressions unless the assignment is wrapped in parentheses.
|
This is a fairly popular idiom among Rubyists that's sometimes referred to as _safe assignment in condition_.
|
[source,ruby]
|
----
|
# bad (+ a warning)
|
if v = array.grep(/foo/)
|
do_something(v)
|
# some code
|
end
|
# good (MRI would still complain, but RuboCop won't)
|
if (v = array.grep(/foo/))
|
do_something(v)
|
# some code
|
end
|
# good
|
v = array.grep(/foo/)
|
if v
|
do_something(v)
|
# some code
|
end
|
----
|
=== `BEGIN` Blocks [[no-BEGIN-blocks]]
|
Avoid the use of `BEGIN` blocks.
|
=== `END` Blocks [[no-END-blocks]]
|
Do not use `END` blocks. Use `Kernel#at_exit` instead.
|
[source,ruby]
|
----
|
# bad
|
END { puts 'Goodbye!' }
|
# good
|
at_exit { puts 'Goodbye!' }
|
----
|
=== Nested Conditionals [[no-nested-conditionals]]
|
Avoid use of nested conditionals for flow of control.
|
Prefer a guard clause when you can assert invalid data.
|
A guard clause is a conditional statement at the top of a function that bails out as soon as it can.
|
[source,ruby]
|
----
|
# bad
|
def compute_thing(thing)
|
if thing[:foo]
|
update_with_bar(thing[:foo])
|
if thing[:foo][:bar]
|
partial_compute(thing)
|
else
|
re_compute(thing)
|
end
|
end
|
end
|
# good
|
def compute_thing(thing)
|
return unless thing[:foo]
|
update_with_bar(thing[:foo])
|
return re_compute(thing) unless thing[:foo][:bar]
|
partial_compute(thing)
|
end
|
----
|
Prefer `next` in loops instead of conditional blocks.
|
[source,ruby]
|
----
|
# bad
|
[0, 1, 2, 3].each do |item|
|
if item > 1
|
puts item
|
end
|
end
|
# good
|
[0, 1, 2, 3].each do |item|
|
next unless item > 1
|
puts item
|
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.