Ruby元编程class_eval [英] Ruby.Metaprogramming. class_eval

查看:59
本文介绍了Ruby元编程class_eval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码似乎有误.但是我只是找不到它.

There seem to be a mistake in my code. However I just can't find it out.

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,2,3].但是,它不会返回任何内容.

I would expect it to return an array [1,2,3]. However, it doesn't return anything.

推荐答案

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

You will find a solution for your problem in Sergios answer. Here an explanation, what's going wrong in your code.

使用

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

您执行

 @bar_history = [1,2,3]

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

You execute this on class level, not in object level. The variable @bar_history is not available in a Foo-object, but in the Foo-class.

使用

puts f.bar_history.to_s

您访问-从不定义对象级别-属性@bar_history.

you access the -never on object level defined- attribute @bar_history.

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

When you define a reader on class level, you have access to your variable:

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

这篇关于Ruby元编程class_eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆