Posts tagged "blocks"

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.


I’d like to start with a question: Have you ever seen code like this?

class User < ActiveRecord::Base
end
 
User.new.tap do |user|
  user.name     = "John Doe"
  user.username = "john.doe"
  user.password = "john123"
end

I have. But what few developers know is that many methods in Active Record already accept a block, so you don’t need to invoke tap in the first place. And that’s all because Active Record loves blocks! Let’s go through some examples.

Using blocks with Active Record

When creating an Active Record object, either by using new or create/create!, you can give a block straight to the method call instead of relying on tap:

User.new do |user|
  user.name     = "John Doe"
  user.username = "john.doe"
  user.password = "john123"
end
 
User.create do |user|
  user.name     = "John Doe"
  user.username = "john.doe"
  user.password = "john123"
end

And you can mix and match with hash initialization:

User.new(name: "John Doe") do |user|
  user.username = "john.doe"
  user.password = "john123"
end

All these methods, when receiving a block, yield the current object to the block so that you can do whatever you want with it. It’s basically the same effect as using tap. And it all happens after the attributes hash have been assigned and other internal Active Record code has been run during the object initialization, except by the after_initialize callbacks.

That’s neat. That means we can stop using tap in a few places now. But wait, there’s more.

Active Record associations also love blocks

We talked about using blocks when building an Active Record object using new or create, but associations like belongs_to or has_many also work with that, when calling build or create on them:

class User < ActiveRecord::Base
  has_many :posts
end
 
class Post < ActiveRecord::Base
  belongs_to :user
end
 
# has_many
user = User.first
user.posts.build do |post|
  post.title = "Active Record <3 Blocks"
  post.body  = "I can give tap a break! <3 <3 <3"
end
 
# belongs_to
post = Post.first
post.build_user do |user|
  user.name     = "John Doe <3 blocks"
  user.username = "john.doe"
  user.password = "john123"
end

That’s even better. That means we can stop using tap in a few more places.

Wrapping up: Active Record <3 blocks

It is possible to avoid extra work, sometimes simple stuff such as using tap with methods like new and create, other times more complicated ones, by getting to know what the framework can give us for free.

There are other places inside Active Record that accept blocks, for instance first_or_initialize and friends will execute the given block when the record is not found, to initialize the new one.

In short, next time you need a block when creating records using Active Record, take a minute to see if you can avoid using tap by using an already existing feature. Remember: Active Record <3 blocks. And don’t do that with blocks only, the main idea here is that you can learn more about the framework, and let it do more work for you.

How about you, do you have any small trick in Ruby or Rails that makes your work easier? Take a minute to share it with others in the comments. :)