module HashInitialized
def hash_initialized(*fields)
define_method(:initialize) do |h|
missing = fields - h.keys
raise Exception, "Not all fields set: #{missing}" if missing.any?
h.each do |k,v|
instance_variable_set("@#{k}", v) if fields.include?(k)
end
end
end
end
class Cheese
extend HashInitialized
attr_accessor :color, :odor, :taste
hash_initialized :color, :odor, :taste
end
好的,我明白了:
任何帮助表示赞赏!
代码取自rubymonk.com,Metaprogramming Ruby:Ascent
答案 0 :(得分:3)
define_method(:initialize) do |h|...
使用一个参数(h
)创建了一个initialize方法。这意味着它会创建一个期望哈希的构造函数。想象一下,创建的代码如下所示:
class Cheese
def initialize(h)
missing = fields - h.keys
raise Exception, "Not all fields set: #{missing}" if missing.any?
h.each do |k,v|
instance_variable_set("@#{k}", v) if fields.include?(k)
end
end
end