Question about exiting from a block

G

Guoliang Cao

def test
puts 'before'
yield 2
puts 'after'
end

test do |i|
XXX if i > 1
# a lot of code appears below
end


I have code above and wonder if it is possible to use
return/break/anything to stop execution of block and return control to
test() to execute code after yield. I know it is impossible in 1.8. How
about 1.9? Does anyone feel this is an important feature to have?

Thank you.
Guoliang Cao
 
J

Joel VanderWerf

Guoliang said:
def test
puts 'before'
yield 2
puts 'after'
end

test do |i|
XXX if i > 1
# a lot of code appears below
end


I have code above and wonder if it is possible to use
return/break/anything to stop execution of block and return control to
test() to execute code after yield. I know it is impossible in 1.8. How
about 1.9? Does anyone feel this is an important feature to have?

It is possible in 1.8, using the next keyword:

def test
puts 'before'
yield 2
puts 'after'
end

test do |i|
next if i > 1
puts "a lot of code"
end
 
M

matt neuburg

Guoliang Cao said:
def test
puts 'before'
yield 2
puts 'after'
end

test do |i|
XXX if i > 1
# a lot of code appears below
end


I have code above and wonder if it is possible to use
return/break/anything to stop execution of block and return control to
test() to execute code after yield. I know it is impossible in 1.8.

Why is it impossible? Doesn't "break" do what you need? (And remember,
"break" and "next" can even return a value from a block to the yielder.)
m.
 
J

Joel VanderWerf

matt said:
Why is it impossible? Doesn't "break" do what you need? (And remember,
"break" and "next" can even return a value from a block to the yielder.)

Nope, break will skip the "after" line.
 
G

Guoliang Cao

Joel said:
It is possible in 1.8, using the next keyword:

def test
puts 'before'
yield 2
puts 'after'
end

test do |i|
next if i > 1
puts "a lot of code"
end

This is great! I never thought of using 'next'.

Thank you!
 
B

Brian Candler

Keeping it simple:

def test
puts 'before'
yield 2
puts 'after'
end

test do |i|
unless i > 1
puts "a lot of code here"
end
end

There's also throw/catch:

test do |i|
catch:)done) do
throw:)done) if i > 1
puts "a lot of code here"
end
end
 
B

Bertram Scharpf

Hi,

Am Freitag, 05. Jun 2009, 06:48:43 +0900 schrieb Joel VanderWerf:
It is possible in 1.8, using the next keyword:

Slightly modified:

def f ; puts "A" ; puts yield ; puts "Z" ; "F" ; end

f { next "X" ; puts "Y" } #=> "F"
puts "-"
f { break "X" ; puts "Y" } #=> "X"

The output is:

A
X
Z
-
A

Will this work in 1.9, too?

Bertram
 

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

Similar Threads


Members online

Forum statistics

Threads
473,774
Messages
2,569,600
Members
45,180
Latest member
CryptoTax Software
Top