How to return value from middle of a block?

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.

Hi:

#i+=1 == 3 ? rtn = nil : rtn = i   

should be

···

On Tuesday, 17 December 2002 at 8:52:44 +0900, Jim Freeze wrote:

#(i+=1) == 3 ? rtn = nil : rtn = i   


Jim Freeze

If you had any brains, you’d be dangerous.

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.

Hi,

···

In message “How to return value from middle of a block?” on 02/12/17, Jim Freeze jim@freeze.org writes:

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

						matz.

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

Hi,

···

At Tue, 17 Dec 2002 11:59:01 +0900, Jim Freeze wrote:

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

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

break' exits closest *lexical* block, try withnext’.


Nobu Nakada