{ |one, step, back| } 1 of 1 article Syndicate: full/short

Braces Vs Do/End   30 Jul 04
[ print link all ]
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.



blog comments powered by Disqus

 

Formatted: 02-Jul-09 23:09
Feedback: jim@weirichhouse.org