我有以下代码用于将哈希集合转换为我的类上的方法(有点像活动记录)。我遇到的问题是我的二传手不工作。我对 Ruby 还是很陌生,相信我已经让自己有所转变。
class TheClass
def initialize
@properties = {"my hash"}
self.extend @properties.to_methods
end
end
class Hash
def to_methods
hash = self
Module.new do
hash.each_pair do |key, value|
define_method key do
value
end
define_method("#{key}=") do |val|
instance_variable_set("@#{key}", val)
end
end
end
end
end
这些方法已创建,我可以在课堂上阅读它们,但设置它们不起作用。
myClass = TheClass.new
item = myClass.property # will work.
myClass.property = item # this is what is currently not working.