Using yield inside define_method in Ruby

前端 未结 2 2038
悲&欢浪女
悲&欢浪女 2020-12-29 03:22

Is it possible to make yield keyword work inside a block given to define_method? Simple example:

class Test
  define_method :test do |&b         


        
2条回答
  •  旧时难觅i
    2020-12-29 04:06

    I think this is what you're looking for:

    class Test
      define_method :test do |&b|
        b.call
      end
    end
    
    Test.new.test {
      puts "Hi!"
    }
    

    More at http://coderrr.wordpress.com/2008/10/29/using-define_method-with-blocks-in-ruby-18/

提交回复
热议问题