From: Ed Howland Date: 2010-10-23T05:09:54+09:00 Subject: Why no yield in 1.9.2 blocks? 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} => # 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 `
' But this works: ruby-1.9.2-p0 > l= lambda {|&blk| blk.call} => # 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"} => # 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