Read more

Ruby blocks: Braces and do/end have different precedence

Henning Koch
April 05, 2012Software engineer at makandra GmbH

TL;DR {} binds stronger than do … end (as always in Ruby, special characters bind stronger than words)

Demo

Right way

names = ['bRUce', 'STaN', 'JOlIE']

# Blocks in braces are passed to the rightmost method
print names.map { |name| name.downcase }
print(names.map do |name| name.downcase end) # equivalent
=> ["bruce", "stan", "jolie"]

Wrong way

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Avoid the examples below, as you pass at least one block to print and not to the enumerator.

names = ['bRUce', 'STaN', 'JOlIE'] 

# Blocks in do…end are passed to the leftmost method
print names.map do |name| name.downcase end
print(names.map) { |name| name.downcase } # equivalent
=> #<Enumerator:0x00000001e793b0>

# Combined
print names.map { |name| name.downcase } do |name| name.capitalize end
print(names.map { |name| name.downcase }) do |name| name.capitalize end # equivalent
=> ["bruce", "stan", "jolie"]
Posted by Henning Koch to makandra dev (2012-04-05 11:11)