Variable Scope in Blocks

ruby

Solution

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.

Problem

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?

Original source

Related problems