Variable area in blocks

David A. Black (The Well Grounded Rubyist, chapter 6) presents the following code:

def block_local_parameter
  x = 100
  [1,2,3].each do |x|
    puts "Parameter x is #{x}"
    x += 10
    puts "Reassigned to x in block; it is now #{x}"
  end
  puts "The value of outer x is now #{x}"
end

block_local_parameter

The expected result according to the book (Ruby 1.9.1):

Parameter x is 1
Reassigned to x in block; it now 11
Parameter x is 2
Reassigned to x in block; it now 12
Parameter x is 3
Reassigned to x in block; it now 13
Outer x is still 100

My conclusion (Ruby 1.8.7):

Parameter x is 1
Reassigned to x in block; it now 11
Parameter x is 2
Reassigned to x in block; it now 12
Parameter x is 3
Reassigned to x in block; it now 13
Outer x is still 13

Is the book wrong? Or am I missing something?

+3
source share
1 answer

What you see is the behavior for Ruby 1.8.x. The variable area for the blocks was introduced in 1.9, will switch to 1.9.x, and you will get the same results as in the book.

+8
source

All Articles