|
The big remaining question on Ruby coding style is: When should you used {
} for blocks, and when should you use do/end?
Blocks in Ruby may be written with brace delimeters or do/end delimiters.
There is a subtle difference in precedence between the two versions, but
for most work the two are identical.
So which way do you go?
Some folk use { } for one-liners and do/end for multi-liners. Others stick
exclusively to either { } or do/end. I tried all of the above, but was
never really satisified with any of the guidelines.
Here is the guideline I use now:
- Use { } for blocks that return values
- Use do / end for blocks that are executed for side effects
This has the advantage of using the choice of block delimiter to convey a
little extra information. Here’s some examples.
# block used only for side effect
list.each do |item| puts item end
# Block used to return test value
list.find { |item| item > 10 }
# Block value used to build new value
list.collect { |item| "-r" + item }
Of course, if precedenence makes a difference, use the type of block that
makes sense. This is just a guideline after all.
But I have found the distinction to be useful.
|