【问题标题】:Why is this returning an error?为什么这会返回错误?
【发布时间】:2012-05-05 13:54:50
【问题描述】:
BasicObject.class_eval do
    def instance(ins)
        eval "@#{ins}=#{ins}", binding
    end
end

是有问题的代码。我想要它做的是在下面的代码中,在类 Foo 中创建一个新的实例变量 bar。 运行此代码后得到的结果:

class Foo
  bar = 3
end
Foo.instance(:bar)

是:

 NameError: undefined local variable or method `bar for Foo:Class
        from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `instance'
        from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `eval'
        from /Users/Solomon/Desktop/Ruby/instance.rb:3:in `instance'

为什么会这样。

【问题讨论】:

  • 与上一个问题中给出的原因相同——一旦处理了类声明,“bar”就不存在了。

标签: ruby class methods eval instance


【解决方案1】:

这里有一些事情......你已经为BasicObject 定义了一个实例方法instance。然后,您将在 Foo 对象上调用此实例方法。 Foo 对象是一个类。您尚未为 Foo 对象设置任何实例变量。您使用@ 符号设置实例变量。 instance 方法所做的只是将实例变量 @ins 设置为自身。

这里也不需要, binding,因为binding 是返回当前变量绑定的顶级方法。如果您需要传递已保存的“环境”,则只需保存binding。拥有, binding 并没有什么坏处,反而是多余的。

 BasicObject.class_eval do
    def instance(ins)
       eval "@#{ins}= @#{ins}", binding      # @ after the '='
    end
 end



class Foo
  @bar = 3     # @ here
end
Foo.instance(:bar)
puts Foo.instance_variable_get("@bar")    # Shows the instance variable @bar for Foo object

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 2014-05-09
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 2015-08-18
    相关资源
    最近更新 更多