I’m a beginner in Ruby, so I’m sorry to ask something so simple, but is there anything wrong with this code –
3.upto(9) {
print "Hello"
puts " World"
}
or
3.upto(9) { |n|
print "Hello "
puts n
}
It works well enough, but most of the code samples I see use the syntax of
3.upto(9) do |n|
print "Hello "
puts n
end
is it just the convention to only use curly braces for single statements? Coming from C/C# the first seems more natural to me, but when in Rome!
There is a subtle difference between the two syntaxes.
{ }are higher precedence thando ... end. Thus, the following will passbarand a block to methodfoo:while the following will pass a block to
bar, and the result of that tofoo:So your examples will act the same. However, if you left the parentheses off:
So,
{ }are more likely to catch you up if you leave off parentheses in Ruby, which is fairly common; for this reason, and because Ruby conditionals and other control constructs all useendas a delimiter, people usually usedo ... endfor multi-line code blocks that come at the end of a statement.However,
{ }is frequently use in places wheredo ... endwould be cumbersome, for instance, if you are chaining several methods together which take blocks. This can allow you to write short, one line little blocks which can be used as part of a method chain.Here’s an example to illustrate this difference: