1
可能重複:
How do I use define_method to create class methods?Ruby中可以使用動態類方法嗎?
我試圖做到這一點:
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
有什麼辦法來定義紅寶石動態類的方法呢?
不錯!這就是我的意思:) – 2010-08-19 20:04:56
這對_every_類定義了等等。 – philomory 2016-06-12 21:01:01