Ruby中的动态类方法是否可行?

时间:2010-08-19 07:11:17

标签: ruby metaprogramming

  

可能重复:
  How do I use define_method to create class methods?

我正在尝试这样做:

class Foo
  class << self
    def runtime_method(*methods)
      methods.each do |name|
        define_method "self.#{name}" do |*args|
          "dynamic class method #{name.inspect}"
        end
        self.class_eval do
          define_method name do
            "dynamic instance method #{name.inspect}"
          end
        end
      end
    end
  end

  runtime_method :foo, :bar
end

puts Foo.foo rescue #=> otherwise, undefined method `foo' for Foo:Class (NoMethodError)
puts Foo.new.foo #=> dynamic instance method: :foo
puts Foo.new.bar #=> dynamic instance method: :bar

有没有办法在ruby中定义动态类方法?

1 个答案:

答案 0 :(得分:3)

我不确定我完全理解你,但这是你的意思吗?

>> class Foo
>> end
=> nil
>> Foo.blah
NoMethodError: undefined method `blah' for Foo:Class
    from (irb):3
>> 
?> Foo.class.class_eval do
?>   def blah
>>     puts "hello"
>>   end
>> end
=> nil
>> Foo.blah
hello
=> nil