From: Logan Capaldo Date: 2007-08-15T10:22:08+09:00 Subject: Re: Can a lambda or Proc object yield a value to a block? ------=_Part_40780_5534680.1187140920564 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On 8/14/07, Cleasai Beag wrote: > > Logan Capaldo wrote: > > You actually can use yield in a block, you just need to realize it's the > > yield of the enclosing scope: > > > > def example > > a_proc = lambda { yield "Hi" } > > > > if block_given? > > a_proc.call > > end > > end > > > > example { |x| puts x } > > Thanks for the reply Logan. Obviously I'll have to study Ruby's scope > rules a bit more. I notice that I can't modify your example as follows > to pass in a lambda object because I get the "LocalJumpError: no block > given" error again. > > a_proc = lambda { yield "Hi" } > > def example2(proc) > > if block_given? > proc.call > end > end > > example2(a_proc) { |x| puts x } > > Presumably the enclosing scope for the lambda object in my example is > outside the scope of the example2 method. It's scope is the scope in > which it was defined which is "nowhere" really i.e. it's outside a > class, module and method. > Presumably because of this it just can't yield a value. Does this sound > plausible at all? > > P.S. What I'm really trying to do is emulate some of things that I've > done before in Scheme. > > For example a generic "each" maker which doesn't work 'cos of the whole > LocalJumpError thing. class Stepper def initialize(next_value, start, stop) @next_value = next_value @start = start @stop = stop end def each x = @start while x <= @stop yield x x = @next_value.call(x) end end end from11to20 = Stepper.new(lambda { |x| x + 1}, 11, 20) from11to20.each { |x| puts x * x } def makeEach(nextValue, start, stop) > lambda do > x = start > while x <= stop > yield x > x = nextValue.call(x) > end > end > end > > from11to20 = makeEach(lambda {|x| x+1}, 11, 20) > > from11to20 {|x| puts x*x} Even if blocks could yield, you'd still have to say from11to20.call { |x| puts x * x } Ruby is a Lisp-2 (like CL), you have to (funcall your lambdas That said, if I really wanted to go from 11 to 20 I'd do 11.upto(20) { |x| puts x * x } or 11.step(20, 1) { |x| puts x * x } -- > Posted via http://www.ruby-forum.com/. > > ------=_Part_40780_5534680.1187140920564--