Blocks
A block in Ruby is more than just a code block or group of statements. A Ruby block is always invoked in conjunction with a method, as you will see. In fact, blocks are closures, sometimes referred to as nameless functions. They are like a method within another method that refers to or shares variables with the enclosing or outer method. In Ruby, the closure or block is wrapped by braces ({}) or by do/end, and depends on the associated method (such as each) to work.
Here is an example call to a block on the method each from
Array:
pacific = [ "Washington", "Oregon", "California" ]
pacific.each do |element|
puts element
end
The name in the bars (|element|) can be any name you want. The block uses it as a local variable to keep track of every element in the array, and later uses it to do something with the element. You can replace do/end with a pair of braces, as is most commonly done. The braces actually have a higher precedence
than do/end:
pacific.each { |e| puts e }
If you use a variable name that already exists in the containing scope, the block assigns that variable each successive value, which may or may not be what you want. It does not generate a local variable to the block with that name, as some might expect. Thus, you get this behavior:
j = 7
(1..4).to_a.each { | j | } # j now equals 4
A block in Ruby is more than just a code block or group of statements. A Ruby block is always invoked in conjunction with a method, as you will see. In fact, blocks are closures, sometimes referred to as nameless functions. They are like a method within another method that refers to or shares variables with the enclosing or outer method. In Ruby, the closure or block is wrapped by braces ({}) or by do/end, and depends on the associated method (such as each) to work.
Here is an example call to a block on the method each from
Array:
pacific = [ "Washington", "Oregon", "California" ]
pacific.each do |element|
puts element
end
The name in the bars (|element|) can be any name you want. The block uses it as a local variable to keep track of every element in the array, and later uses it to do something with the element. You can replace do/end with a pair of braces, as is most commonly done. The braces actually have a higher precedence
than do/end:
pacific.each { |e| puts e }
If you use a variable name that already exists in the containing scope, the block assigns that variable each successive value, which may or may not be what you want. It does not generate a local variable to the block with that name, as some might expect. Thus, you get this behavior:
j = 7
(1..4).to_a.each { | j | } # j now equals 4
No comments:
Post a Comment