Understanding blocks in Ruby on Rails
December 6, 2008 – 6:32 pmUnderstanding how to use blocks in Ruby is crucial to leveraging the full power of this language.
A block, known as a closure in programming theory, is basically just a method without a name, or an anonymous method. All methods in Ruby have the special ability to accept a block as a parameter. The method is converted into an object, an instance of the Proc class.
99.downto(1) { |num| puts "The number is #{num}" }
Consider the example above. 99 is an object. Remember everything is an object in Ruby. “downto” is a method which takes the integer 1 as a parameter. However, it also takes the block (in the curly braces) as a parameter. The downto method will iterate over the numbers, temporarily passing control to the attached block on each iteration. Any parameters for the anonymous method or block are placed between the goal posts | |. If there are no parameters then the goal posts can be left out. The remainder of the block is just normal Ruby code the same as any other method.
An example of how the downto method might be implemented is shown below. The special yield keyword passes control to the attached block during each iteration.
def downto(value)
n = self #self represents the object 99
while n >= value
yield n #yield control to the attached block passing n as the parameter
n -= 1
end
return self
end
Note also, if you explicitly pass a method as a parameter, you can access that method as follows:
def some_method(&block)
...
block.call <parameters>
...
end
call is a method of the Proc class.
Note also, you can use do and end instead of { and } for blocks. They can be used interchangeably.