Ruby 如何对多属性值使用class_eval
我试图扩展保存属性值记录的方法。但是,如果有多个属性,我的代码就会失败。代码如下:Ruby 如何对多属性值使用class_eval,ruby,Ruby,我试图扩展保存属性值记录的方法。但是,如果有多个属性,我的代码就会失败。代码如下: class Class def attr_accessor_with_history(attr_name) attr_name = attr_name.to_s attr_reader attr_name ah=attr_name+"_history" attr_reader ah class_eval %Q{ def #{attr
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
attr_reader attr_name
ah=attr_name+"_history"
attr_reader ah
class_eval %Q{
def #{attr_name}= (attr_name)
@attr_name=attr_name
if @ah == nil
@ah=[nil]
end
@ah.push(attr_name)
end
def #{ah}
@ah
end
def #{attr_name}
@attr_name
end
}
end
end
这里有一个用于测试的虚拟类
class Foo
attr_accessor_with_history :bar
attr_accessor_with_history :bar1
end
f = Foo.new
f.bar = 1
f.bar = 2
f.bar1 = 5
p f.bar_history
p f.bar1_history
出于某种原因,
f.bar
和f.bar1
都返回5
和f.bar\u history=f.bar1\u history=[nil,1,2,5]
。知道为什么吗?在获取/设置方法时,您使用的是@ah
和@attr\u name
而不是{ah}
和{attr\u name}
。这意味着它们总是设置并返回相同的实例变量,而不是不同的、动态命名的实例变量
class Class
def attr_accessor_with_history(attr_name)
class_eval %{
attr_reader :#{attr_name}, :#{attr_name}_history
def #{attr_name}=(value)
@#{attr_name} = value
@#{attr_name}_history ||= [nil]
@#{attr_name}_history << value
end
}
end
end
类
def attr_访问器_和_历史记录(attr_名称)
等级评估%{
属性读取器:{attr_name},:{attr_name}
def#{attr_name}=(值)
@#{attr_name}=value
@#{attr_name}|u history |=[nil]
@#{attr_name}\u history{attr_name}\u history
方法的代码在哪里?哎呀,我没有复制整个代码哇。这很有效。非常感谢(也谢谢你清理了我的代码:D)。顺便问一下,你有什么好的、简短的Ruby介绍书(或教程)可以推荐吗?我借用了“Ruby编程语言”但是它有点冗长。请不要忘了:)
。这本书(又名鹤嘴锄)被认为是权威的Ruby书,尽管有人声称它有点密集(我只是零碎地读了它,所以我真的不能评论太多)。也是非常受尊敬的。我的大部分Ruby知识来自于与他人合作,阅读大量代码,当然还有大量的写作。(也就是说,没有一个简短的教程会涉及到您在这里所做的元编程。)