加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby.Metaprogramming. class_eval

发布时间:2020-12-16 20:52:42 所属栏目:百科 来源:网络整理
导读:我的代码中似乎有一个错误.但是我无法找到它. class Classdef 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=
我的代码中似乎有一个错误.但是我无法找到它.
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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读