Tag: 类eval

`class_eval`字符串中的变量范围是什么?

我正在使用class_eval编写要在当前类的上下文中执行的代码。 在以下代码中,我想为属性值的更改添加计数器。 class Class def attr_count(attr_name) attr_name = attr_name.to_s attr_reader attr_name # create the attribute’s getter class_eval %Q{ @count = 0 def #{attr_name}= (attr_name) @attr_name = attr_name @count += 1 end def #{attr_name} @attr_name end } end end class Foo attr_count :bar end f = Foo.new f.bar = 1 我对class_eval理解是它在运行时类的上下文中计算块 – 在我的例子中,在class Foo 。 我希望上面的代码运行类似于 […]

Ruby – 使用class_eval定义方法

我正在做SaaS Stanford课程,试图完成这项任务的第5部分 我很难掌握这个概念,这就是我试图做的事情: class Class def attr_accessor_with_history(attr_name) attr_name = attr_name.to_s attr_reader attr_name attr_reader attr_name + ‘_history’ class_eval %Q'{def #{attr_name}(a);#{attr_name}_history.push(a) ; end;}’ end end 我可能做错了各种各样的事情,阅读关于元编程的The Book of Ruby章节,我仍然没有得到它,有人能帮助我理解这一点吗?