question about blocks

F

Ferenc Engard

Hello,

How can I return a value from a block? "return" immediately returns from
the caller method, "break" bypasses the called method (which yielded the
block).

I have read something about this, but cannot remember where. I know the
syntax changed between 1.6.8 and 1.8.

Ferenc
 
S

Simon Strandgaard

How can I return a value from a block? "return" immediately returns from
the caller method, "break" bypasses the called method (which yielded the
block).

I have read something about this, but cannot remember where. I know the
syntax changed between 1.6.8 and 1.8.

How about this code?


server> ruby a.rb
before
after result=42
server> expand -t2 a.rb
def test(&block)
puts "before"
res = nil
begin
res = block.call
rescue LocalJumpError => e
res = e.exit_value
end
puts "after result=#{res}"
end

test { return 42 }
server>
 
J

Jamis Buck

Simon said:
How about this code?


server> ruby a.rb
before
after result=42
server> expand -t2 a.rb
def test(&block)
puts "before"
res = nil
begin
res = block.call
rescue LocalJumpError => e
res = e.exit_value
end
puts "after result=#{res}"
end

test { return 42 }
server>

By way of explanation, I believe the difference is this: when the block
is invoked implicitly (via 'yield') a 'return' or 'break' will affect a
scope greater than itself (not sure if my terminology is correct here).
When the block is invoked explicitly (via the 'call' method of Proc),
then 'return' and 'break' affect only the block itself.

Perhaps some Ruby guru could verify whether this is accurate or not.
This seems to be the behavior as I've seen it, at least according to my
few forays into the Ruby source code.
 
N

nobu.nokada

Hi,

At Wed, 21 Jan 2004 05:37:48 +0900,
Ferenc said:
How can I return a value from a block? "return" immediately returns from
the caller method, "break" bypasses the called method (which yielded the
block).

next value
 

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
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top