Do End Your Braces

Mike Burns

Braces and do/end are completely swappable—almost all the time. They have different precedence. It’s not often that anyone comes across what this means in practice.

In shoulda, these do different things:

should redirect_to('#edit') { article_edit_path(@article) }
should redirect_to('#edit') do
  article_edit_path(@article)
end

To get a better grasp on the differences, consider these two simple methods:

def outer(inner, &block)
  inner
  block.call('outer') if block_given?
end

def inner(&block)
  block.call('inner') if block_given?
  1
end

Here outer is analogous to should and inner to redirect_to. Instead of having any real logic, though, they call a block with what they are. In practice:

outer inner {|where| puts "#{where} called me"}

# "inner called me"

outer inner do |where|
  puts "#{where} called me"
end

# "outer called me"

''

author image
Mike Burns

Pair with one of our expert developers to level up your skills with Coaching by thoughtbot. Save time learning best practices and techniques for reducing technical debt in Ember, Ruby, Haskell, and Go in 1-on-1 sessions tailored to your goals.