Hi:
I am trying to return a value from a middle of a block,
but when I do, it exits the block.
Here is the code:
def _parse
loop { puts yield }
end
def parse
i = 0
_parse {
# This code returns nil, but keeps going.
# prints
# 1
# 2
# nil
# …
#i+=1 == 3 ? rtn = nil : rtn = i
#rtn
# This code quits when it see return
# prints
# 1
# 2
i += 1
if i == 3
return nil
end
i
}
end
parse
Is there a syntax for returning a value from the middle of
a block? I know that I can always set a return value and
let execution drop to the bottom of the block, but it is
discomforting for there to be a difference betweeen
an implicit return and an explicit return.
···
–
Jim Freeze
Hofstadter’s Law:
It always takes longer than you expect, even when you take
Hofstadter’s Law into account.
Jim Freeze jim@freeze.org writes:
Is there a syntax for returning a value from the middle of
a block? I know that I can always set a return value and
Is this what you’re looking for?
def bar
100.times{|i| puts yield i}
end
def foo
if arg < 10
return 10 #explicit return
end
arg #implicit return
end
bar{|i| foo(i)}
YS.
Hmm, I tried that, but it didn’t work.
→ ./ruby173/bin/ruby -v
ruby 1.7.3 (2002-12-04) [i386-freebsd4.6]
→ cat p1.rb
def _parse
loop { puts yield }
end
def parse
i = 0
_parse {
#(i+=1) == 3 ? rtn = nil : rtn = i
#rtn
if (i+=1) == 3
break nil
end
i
}
end
parse
→ ./ruby173/bin/ruby p1.rb
1
2
···
On Tuesday, 17 December 2002 at 9:07:13 +0900, Yukihiro Matsumoto wrote:
Hi,
I am trying to return a value from a middle of a block,
but when I do, it exits the block.
break
if you’re using 1.7
–
Jim Freeze
“If I had only known, I would have been a locksmith.”
– Albert Einstein