Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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]

大佬总结

以上是大佬教程为你收集整理的Ruby.Metaprogramming. class_eval全部内容,希望文章能够帮你解决Ruby.Metaprogramming. class_eval所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: