When we start programming with Ruby, one of the first niceties we learn about are the Ruby blocks. In the beginning it’s easy to get tricked by the two existing forms of blocks and when to use each:
%w(a b c).each { |char| puts char }
%w(a b c).each do |char| puts char end
The Ruby Community has sort of created a “guideline” for when to use one versus another: for short or inline blocks, use curly brackets {..}
, for longer or multiline blocks, use the do..end
format. But did you know there is actually a slight difference between them? So sit tight, we’ll cover it now.
Operators Precedence
Languages contain operators, and these operators must obey a precedence rule so that the interpreter knows the order of execution, which means one operator will be executed first if it has higher precedence than others in a piece of code. Consider the following example:
a || b && c
What operation gets executed first, a || b
, or b && c
? This is where operator precedence takes action. In this case, the code is the same as this:
a || (b && c)
Which means &&
has higher precedence than ||
in Ruby. However, if you want the condition a || b
to be evaluated first, you can enforce it with the use of ()
:
(a || b) && c
This way you are explicitly telling the interpreter that the condition inside the ()
should be executed first.
What about blocks?
It turns out blocks have precedence too! Lets see an example that mimics the Rails router with the redirect
method:
def get(path, options = {}, &block)
puts "get received block? #{block_given?}"
end
def redirect(&block)
puts "redirect received block? #{block_given?}"
end
puts '=> brackets { }'
get 'eggs', to: redirect { 'eggs and bacon' }
puts
puts '=> do..end'
get 'eggs', to: redirect do 'eggs and bacon' end
This example shows a rather common code in Rails apps: a get
route that redirects to some other route in the app (some arguments from the real redirect
block were omitted for clarity). And all these methods do is outputting whether they received a block or not.
At a glance these two calls to get + redirect
could be considered exact the same, however they behave differently because of the blocks precedence. Can you guess what’s the output? Take a look:
=> brackets {..}
redirect received block? true
get received block? false
=> do..end
redirect received block? false
get received block? true
The curly brackets have higher precedence than the do..end
, which means the block with {..}
will attach to the inner method, in this example redirect
, whereas the do..end
will attach to the outer method, get
.
Wrapping up
This blog post originated from a real Rails issue, where you can read a little bit more about the subject and see that even Rails got it wrong in its documentation (which is now fixed). The precedence is a subtle but important difference between {..}
and do..end
blocks, so be careful not to be caught off guard by it.
Do you know any other interesting fact about Ruby blocks that people may not be aware of? Or maybe you learned something tricky about Ruby recently? Please share it on the comments section, we would love to hear.
Could you please demonstrate when && has higher precedence than ||, please? In my example it evaluates from left to right: https://gist.github.com/avsej/fab6d390b0c0fbe4dfbd
Hello Sergey, thanks for asking. I think I was bad at choosing the word `first` to explain the conditions, as it doesn’t actually mean `first` but `grouped together`.
In your example, `a` is evaluated first indeed, but since it returns `nil`, the next evaluation will be `b && c` rather than `nil || b`. That’s what I tried to show with the examples, I’ll update the text and remove the mention to `first`.
Does it answer your question? Thanks for pointing that out.
oh, right, I see how my example is broken. Thanks for pointing out and for article
Beautifully explained 🙂
Thanks Cássio 🙂
Thanks for providing information of Ruby blocks precedence inruby on rails outsourcing.
Awesome article/example! I wrote a similar example to keep it save in my mind. 😀
Thanks!
https://gist.github.com/scudelletti/d74a85cdd7b39a735ff6
Nice, thank you for your feedback and for sharing the gist! 🙂
Also worth noting about block conventions: https://github.com/bbatsov/ruby-style-guide/issues/162
Thanks for sharing. We don’t particularly follow that as a convention, but it’s good for people to know that it exists and have it in mind :).
Nice, really interesting.
The issue on Github helps to understand how this problem may occur on real projects.