Yueyoum
Yueyoum

Reputation: 3073

Ruby block parameters has the same name of local variable

In ruby docs, there is this text:

Block parameters are actually local variables. If an existing local of the same name exists when the block executes, that variable will be modified by the call to the block. This may or may not be a good thing.

I wrote the code below to test this:

x = 0
3.upto(6) {|x| puts x}
puts x

# output are:
# 3
# 4
# 5
# 6
# 0

The variable x is not changed. Why? This is against the docs.

Upvotes: 2

Views: 334

Answers (1)

Dominik Honnef
Dominik Honnef

Reputation: 18430

In Ruby 1.8 and earlier, that was the case. Beginning with 1.9, block variables shadow local variables.

So, in a nutshell: The docs you are reading and the Ruby you are testing with are not of the same version.

Upvotes: 8

Related Questions