[Ruby] Block and variable scope
Block and variable scope Block have direct access to variables that already exist: x = "original x" 1. times do x = 200 end puts x # => 200 But if the name x is used as a block parameter, it'll be a totally different variable from the variable x that already ...
Block and variable scope
Block have direct access to variables that already exist:
x = "original x" 1.times do x = 200 end puts x # => 200
But if the name x is used as a block parameter, it'll be a totally different variable from the variable x that already exists. Therefore, you can use whatever name for block parameters you like, and don't have to worry about confict.
x = "original x" (1..3).each do |x| puts "Parameter x in block is #{x}." end puts "Outer x is still #{x}." # Output: # Parameter x in block is 1. # Parameter x in block is 2. # Parameter x in block is 3. # Outer x is still original x.
Sometimes you may want to use extra temporary variables inside a block, even if it isn’t one of the parameters being assigned to when the block is called. And when you do this, it’s nice not to have to worry that you’re accidentally reusing a variable from outside the block. Ruby provides a special notation indicating that you want one or more variables to be local to the block, even if variables with the same name already exist: a semicolon in the block parameter list.
x = "original x" y = "original y" 2.times do |i;x,y| x = i; y = i + 1; puts "x in block is now #{x}" puts "y in block is now #{y}" end puts "x after block ended is #{x}" puts "y after block ended is #{y}" # Output: # x in block is now 0 # y in block is now 1 # x in block is now 1 # y in block is now 2 # x after block ended is original x # y after block ended is original y
Source: The Well-grounded Rubyist, 2nd Edition (p176) by David Black