I159
I159

Reputation: 31109

Ruby: unexpected semicolon in block parameters

I just started learning Ruby. I typed the example:

x = 10
5.times do |y; x|
  x = y
  puts "x inside the block: #{x}"
end
puts "x outside the block: #{x}"

And I have an error:

hello.rb:3: syntax error, unexpected ';', expecting '|' 5.times do |y; x|

Explain to me please what does it mean? This code should works, as I understand the chapter.

Upvotes: 4

Views: 1107

Answers (1)

Dave Newton
Dave Newton

Reputation: 160181

That's a new 1.9 construct called block local arguments, you're using 1.8.


It also works with lambdas (including stabbed), which is nice:

> x = 42
> love_me = ->(y; x) do
*   x = y
*   puts "x inside the block: #{x}"
* end
> 2.times &love_me
x inside the block: 0
x inside the block: 1
> puts "x outside the block: #{x}"
x outside the block: 42

Upvotes: 9

Related Questions