Ruby.Metaprogramming. class_eval

我的代码中似乎有一个错误.但是我无法找到它.
class Class
def attr_accessor_with_history(attr_name)
  attr_name = attr_name.to_s

  attr_reader attr_name
  attr_writer attr_name

  attr_reader attr_name + "_history"
  class_eval %Q{
   @#{attr_name}_history=[1,2,3]
  }

end
end

class Foo
 attr_accessor_with_history :bar
end

f = Foo.new
f.bar = 1
f.bar = 2
puts f.bar_history.to_s

我希望它返回一个数组[1,3].但是,它不返回任何东西.

解决方法

您将在 Sergios answer中找到解决问题的方法.这里有一个解释,代码中出了什么问题.

class_eval %Q{
 @#{attr_name}_history=[1,3]
}

你执行

@bar_history = [1,3]

您在类级别而不是在对象级别执行此操作.
变量@bar_history在Foo对象中不可用,但在Foo类中不可用.

puts f.bar_history.to_s

您在对象级别定义属性@bar_history上访问-never.

在类级别定义阅读器时,您可以访问您的变量:

class << Foo 
  attr_reader :bar_history
end
p Foo.bar_history  #-> [1,3]

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...