text stringlengths 0 444 |
|---|
=== Indent `when` to `case` [[indent-when-to-case]] |
Indent `when` as deep as `case`. |
[source,ruby] |
---- |
# bad |
case |
when song.name == 'Misty' |
puts 'Not again!' |
when song.duration > 120 |
puts 'Too long!' |
when Time.now.hour > 21 |
puts "It's too late" |
else |
song.play |
end |
# good |
case |
when song.name == 'Misty' |
puts 'Not again!' |
when song.duration > 120 |
puts 'Too long!' |
when Time.now.hour > 21 |
puts "It's too late" |
else |
song.play |
end |
---- |
.A Bit of History |
**** |
This is the style established in both "The Ruby Programming Language" and "Programming Ruby". |
Historically it is derived from the fact that `case` and `switch` statements are not blocks, hence should not be indented, and the `when` and `else` keywords are labels (compiled in the C language, they are literally labels for `JMP` calls). |
**** |
=== Indent Conditional Assignment [[indent-conditional-assignment]] |
When assigning the result of a conditional expression to a variable, preserve the usual alignment of its branches. |
[source,ruby] |
---- |
# bad - pretty convoluted |
kind = case year |
when 1850..1889 then 'Blues' |
when 1890..1909 then 'Ragtime' |
when 1910..1929 then 'New Orleans Jazz' |
when 1930..1939 then 'Swing' |
when 1940..1950 then 'Bebop' |
else 'Jazz' |
end |
result = if some_cond |
calc_something |
else |
calc_something_else |
end |
# good - it's apparent what's going on |
kind = case year |
when 1850..1889 then 'Blues' |
when 1890..1909 then 'Ragtime' |
when 1910..1929 then 'New Orleans Jazz' |
when 1930..1939 then 'Swing' |
when 1940..1950 then 'Bebop' |
else 'Jazz' |
end |
result = if some_cond |
calc_something |
else |
calc_something_else |
end |
# good (and a bit more width efficient) |
kind = |
case year |
when 1850..1889 then 'Blues' |
when 1890..1909 then 'Ragtime' |
when 1910..1929 then 'New Orleans Jazz' |
when 1930..1939 then 'Swing' |
when 1940..1950 then 'Bebop' |
else 'Jazz' |
end |
result = |
if some_cond |
calc_something |
else |
calc_something_else |
end |
---- |
=== Empty Lines between Methods [[empty-lines-between-methods]] |
Use empty lines between method definitions and also to break up methods into logical paragraphs internally. |
[source,ruby] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.