3

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

Expected output as per the book (Ruby 1.9.1):

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

My output (Ruby 1.8.7):

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

Is the book wrong? Or, am I missing something?

sawa
  • 165,429
  • 45
  • 277
  • 381
Prakhar
  • 3,486
  • 17
  • 44
  • 61
  • I think it's sometimes called shadowing, but to be honest I don't know what the word means: http://stackoverflow.com/questions/6259314/what-does-shadowing-mean-in-ruby – Andrew Grimm Jun 06 '11 at 23:53

1 Answers1

8

What you're seeing is the behavior for Ruby 1.8.x. Variable scope for blocks was introduced in 1.9, switch to 1.9.x and you will get the same results as in the book.

edgerunner
  • 14,873
  • 2
  • 57
  • 69