请解释一下ruby的元编程魔力
好吧,我的理解是:请解释一下ruby的元编程魔力,ruby,metaprogramming,Ruby,Metaprogramming,好吧,我的理解是: 我们使用HashInitialized中的方法扩展了类Cheese,因此从模块HashInitialized中初始化的方法hash_可以作为类方法在Cheese中使用 我们将3个符号传递给hash_初始化方法 在hash_初始化方法中,由于*运算符,这3个符号被放入名为fields的数组中 在hash_initialized method中,我们定义了initialize方法 现在这是我不明白的部分,“h”指的是什么?为什么我们可以在| h |上调用h.keys。看起来像是杂
定义方法(:初始化)do | h |…
创建了一个带有一个参数的初始化方法(h
)。这意味着它创建了一个需要散列的构造函数。假设创建的代码如下所示:
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
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