E
Ed Howland
Hi,
I searched in vain for the answer, but why doesn't yield work inside
Ruby 192 blocks. The syntax allows you to pass the blocks as a &blk
param, but you have to call the block with blk.call. If you try to use
yield, you get a LocalJumpError:
ruby-1.9.2-p0 > l= lambda {|&blk| yield}
=> #<Proc:0x000001009d4ad0@(irb):2 (lambda)>
ruby-1.9.2-p0 > l.call {puts 1}
LocalJumpError: no block given (yield)
from (irb):2:in `block in irb_binding'
from (irb):3:in `call'
from (irb):3
from /Users/edh/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
But this works:
ruby-1.9.2-p0 > l= lambda {|&blk| blk.call}
=> #<Proc:0x000001009dc910@(irb):4 (lambda)>
ruby-1.9.2-p0 > l.call {puts 1}
1
=> nil
At least it agrees with block_given?
ruby-1.9.2-p0 > l=lambda {|&blk| puts "block given" if block_given?;
puts "done"}
=> #<Proc:0x00000101825f30@(irb):6 (lambda)>
ruby-1.9.2-p0 > l.call
done
=> nil
ruby-1.9.2-p0 > l.call {puts 1}
done
=> nil
I can live with block.call instead of yield, but no block_given?
Why would you want to pass a block to a block? Why not? so you can do
things like:
def meth(x, &block)
if block_given?
block.call(x) do |y|
puts "in meth " + y.to_s
end
end
end
ruby-1.9.2-p0 > meth(1) {|x, &blk| puts "in blok " + x.to_s; blk.call 2}
in blok 1
in meth 2
[Note, trying this with yield leads to a SyntaxError.]
Cheers,
Ed
Ed Howland
http://greenprogrammer.wordpress.com
http://twitter.com/ed_howland
I searched in vain for the answer, but why doesn't yield work inside
Ruby 192 blocks. The syntax allows you to pass the blocks as a &blk
param, but you have to call the block with blk.call. If you try to use
yield, you get a LocalJumpError:
ruby-1.9.2-p0 > l= lambda {|&blk| yield}
=> #<Proc:0x000001009d4ad0@(irb):2 (lambda)>
ruby-1.9.2-p0 > l.call {puts 1}
LocalJumpError: no block given (yield)
from (irb):2:in `block in irb_binding'
from (irb):3:in `call'
from (irb):3
from /Users/edh/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'
But this works:
ruby-1.9.2-p0 > l= lambda {|&blk| blk.call}
=> #<Proc:0x000001009dc910@(irb):4 (lambda)>
ruby-1.9.2-p0 > l.call {puts 1}
1
=> nil
At least it agrees with block_given?
ruby-1.9.2-p0 > l=lambda {|&blk| puts "block given" if block_given?;
puts "done"}
=> #<Proc:0x00000101825f30@(irb):6 (lambda)>
ruby-1.9.2-p0 > l.call
done
=> nil
ruby-1.9.2-p0 > l.call {puts 1}
done
=> nil
I can live with block.call instead of yield, but no block_given?
Why would you want to pass a block to a block? Why not? so you can do
things like:
def meth(x, &block)
if block_given?
block.call(x) do |y|
puts "in meth " + y.to_s
end
end
end
ruby-1.9.2-p0 > meth(1) {|x, &blk| puts "in blok " + x.to_s; blk.call 2}
in blok 1
in meth 2
[Note, trying this with yield leads to a SyntaxError.]
Cheers,
Ed
Ed Howland
http://greenprogrammer.wordpress.com
http://twitter.com/ed_howland