In the code below, a block, { x += 1 } is magically passed to
thrice ?? or something like that.
I don't understand the usage of the "thrice { iterator }" using {}
and why I can't make a normal block syntax work. The thrice method
doesn't take (normal) parameters, so how does this work?
Ruby, Have you been messing around behind my back?
Thanks in advance.
def thrice
yield
yield
yield
end
x = 5
puts "value of x before: #{x}" # => 5
thrice { x += 1 }
puts "value of x after: #{x}" # => 8
# broken from here down
thrice { |x| x += 1 }
thrice do |x|
x += 1
end
Ruby Freak wrote:
In the code below, a block, { x += 1 } is magically passed to
thrice ?? or something like that.
I don't understand the usage of the "thrice { iterator }" using {}
and why I can't make a normal block syntax work. The thrice method
doesn't take (normal) parameters, so how does this work?
Ruby, Have you been messing around behind my back?
Thanks in advance.
def thrice
yield
yield
yield
end
x = 5
puts "value of x before: #{x}" # => 5
thrice { x += 1 }
puts "value of x after: #{x}" # => 8
# broken from here down
thrice { |x| x += 1 }
thrice do |x|
x += 1
end
In the first case, x in the block refers to the x defined outside the
block. In the 2nd and 3rd cases, you've used x as an argument so it
hides the x outside the block. Any changes you make to x-the-argument
are lost each time the block exits.
···
--
Posted via http://www.ruby-forum.com/\.
Ruby Freak wrote:
def thrice
yield
yield
yield
end
[...]
# broken from here down
thrice { |x| x += 1 }
You're passing a block that takes one argument (x) to a method that yields
none. Also: it's usually not a good idea, to reassign a block argument. That
almost certainly does not do what you want.
HTH,
Sebastian
···
--
Jabber: sepp2k@jabber.org
ICQ: 205544826
Thank you,
I had to get my head around what seems in my mind to be a "backwards
assignment" in code blocks.
Oh. that way!
now it makes perfect sense.