text stringlengths 0 444 |
|---|
# note that elem is accessible outside of the for loop |
elem # => 3 |
# good |
arr.each { |elem| puts elem } |
# elem is not accessible outside each block |
elem # => NameError: undefined local variable or method `elem' |
---- |
=== `then` in Multi-line Expression [[no-then]] |
Do not use `then` for multi-line `if`/`unless`/`when`/`in`. |
[source,ruby] |
---- |
# bad |
if some_condition then |
# body omitted |
end |
# bad |
case foo |
when bar then |
# body omitted |
end |
# bad |
case expression |
in pattern then |
# body omitted |
end |
# good |
if some_condition |
# body omitted |
end |
# good |
case foo |
when bar |
# body omitted |
end |
# good |
case expression |
in pattern |
# body omitted |
end |
---- |
=== Condition Placement [[same-line-condition]] |
Always put the condition on the same line as the `if`/`unless` in a multi-line conditional. |
[source,ruby] |
---- |
# bad |
if |
some_condition |
do_something |
do_something_else |
end |
# good |
if some_condition |
do_something |
do_something_else |
end |
---- |
=== Ternary Operator vs `if` [[ternary-operator]] |
Prefer the ternary operator(`?:`) over `if/then/else/end` constructs. |
It's more common and obviously more concise. |
[source,ruby] |
---- |
# bad |
result = if some_condition then something else something_else end |
# good |
result = some_condition ? something : something_else |
---- |
=== Nested Ternary Operators [[no-nested-ternary]] |
Use one expression per branch in a ternary operator. |
This also means that ternary operators must not be nested. |
Prefer `if/else` constructs in these cases. |
[source,ruby] |
---- |
# bad |
some_condition ? (nested_condition ? nested_something : nested_something_else) : something_else |
# good |
if some_condition |
nested_condition ? nested_something : nested_something_else |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.