How do you pass arguments to define_method?

后端 未结 4 873
走了就别回头了
走了就别回头了 2020-12-12 10:52

I would like to pass an argument(s) to a method being defined using define_method, how would I do that?

4条回答
  •  长情又很酷
    2020-12-12 11:00

    In addition to Kevin Conner's answer: block arguments do not support the same semantics as method arguments. You cannot define default arguments or block arguments.

    This is only fixed in Ruby 1.9 with the new alternative "stabby lambda" syntax which supports full method argument semantics.

    Example:

    # Works
    def meth(default = :foo, *splat, &block) puts 'Bar'; end
    
    # Doesn't work
    define_method :meth { |default = :foo, *splat, &block| puts 'Bar' }
    
    # This works in Ruby 1.9 (modulo typos, I don't actually have it installed)
    define_method :meth, ->(default = :foo, *splat, &block) { puts 'Bar' }
    

提交回复
热议问题