【问题标题】:How to define instance method in ruby dynamically?如何在ruby中动态定义实例方法?
【发布时间】:2012-07-04 02:08:51
【问题描述】:

我想通过父类的类方法动态创建子类的实例方法。

class Foo
  def self.add_fizz_method &body
    # ??? (This is line 3)
  end
end

class Bar < Foo
end
Bar.new.fizz #=> nil

class Bar
  add_fizz_method do
    p "i like turtles"
  end
end
Bar.new.fizz #=> "i like turtles"

在第 3 行写什么?

【问题讨论】:

    标签: ruby metaprogramming


    【解决方案1】:
    define_method 'fizz' do
      puts 'fizz'
    end
    

    ...或接受一个块

    define_method 'fizz', &block
    

    【讨论】:

      【解决方案2】:

      像这样使用define_method

      class Foo
        def self.add_fizz_method &block
          define_method 'fizz', &block
        end
      end
      
      class Bar < Foo; end
      
      begin
        Bar.new.fizz 
      rescue NoMethodError
        puts 'method undefined'
      end
      
      Bar.add_fizz_method do
        p 'i like turtles'
      end
      Bar.new.fizz
      

      输出:

      method undefined
      "i like turtles"
      

      【讨论】:

      • 几乎是我需要的。问题是 - &block 的 self 应该是 Bar 的实例。所以有可能写这样的东西: class Bar ; add_fizz_method 做; p self.bar_name ;结尾 ;结束
      • p 'i like turtles' 下方尝试p self.classself 已经是 Bar 的一个实例。
      • 顺便说一句:如果你想在调用add_fizz_method之前返回nil而不是抛出NoMethodError,你可以在Foo类中声明一个空的fizz方法。跨度>
      • 嘿...我之前写过define_method 'fizz', do &amp;block.call end。特维姆。得到了我需要的东西并学到了东西。
      猜你喜欢
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 2018-02-09
      相关资源
      最近更新 更多