Ruby.Metaprogramming. class_eval

前端之家收集整理的这篇文章主要介绍了Ruby.Metaprogramming. class_eval前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的代码中似乎有一个错误.但是我无法找到它. @H_403_2@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中找到解决问题的方法.这里有一个解释,代码中出了什么问题.

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

你执行

@H_403_2@@bar_history = [1,3]

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

@H_403_2@puts f.bar_history.to_s

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

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

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

猜你在找的Ruby相关文章