Question on passing blocks

R

Ruby Freak

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
 
T

Tim Hunter

Ruby said:
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.
 
S

Sebastian Hungerecker

Ruby said:
def thrice
=A0 =A0 yield
=A0 =A0 yield
=A0 =A0 yield
end
[...]
# broken from here down

thrice =A0{ |x| x +=3D 1 }

You're passing a block that takes one argument (x) to a method that yields=
=20
none. Also: it's usually not a good idea, to reassign a block argument. Tha=
t=20
almost certainly does not do what you want.

HTH,
Sebastian
=2D-=20
Jabber: (e-mail address removed)
ICQ: 205544826
 
R

Ruby Freak

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top