Posted over 10 years ago. Visible to the public. Repeats. Linked content.

Ruby blocks: Braces and do/end have different precedence

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


Right way

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

Wrong way

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 do |name| name.downcase end print( { |name| name.downcase } # equivalent => #<Enumerator:0x00000001e793b0> # Combined print { |name| name.downcase } do |name| name.capitalize end print( { |name| name.downcase }) do |name| name.capitalize end # equivalent => ["bruce", "stan", "jolie"]

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Henning Koch
Last edit:
6 months ago
by Henning Koch
ruby, lambda, proc, block
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more