2

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.

1
  • It wont the x in enumerator is block parameter it scope is limited inside the block only where as the other x is scope in through out the code Commented Oct 28, 2012 at 14:49

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.