Using yield inside define_method in Ruby

前端 未结 2 2029
悲&欢浪女
悲&欢浪女 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条回答
  • 2020-12-29 03:51

    You cannot use yield inside a define_method block. This is because blocks are captured by closures, observe:

    def hello
      define_singleton_method(:bye) { yield }
    end
    
    hello { puts "hello!" }
    
    bye {  puts "bye!" } #=> "hello!"
    

    I don't think your users will mind not being able to use 'yield' in the way you state ---- the syntax is nothing like ordinary Ruby method definition syntax so there is unlikely to be any confusion.

    More information on why you cannot pass blocks implicitly to methods found here: http://banisterfiend.wordpress.com/2010/11/06/behavior-of-yield-in-define_method/

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题