新手问题 eval 方式添加对象属性排错

LinuxGit · 2015年04月21日 · 最后由 linuxgit 回复于 2015年04月21日 · 1853 次阅读

元编程第 6 章:

def add_checked_attribute(klass, attribute)
  eval "
    class #{klass}
      def #{attribute}=(value)
        raise 'Invalid attribute' unless value
        @#{attribute} = value
      end

      def #{attribute}()
        @#{attribute}
      end
    end
  "
end

add_checked_attribute(String, :my_attr)

"Daniel".my_attr = "ruby"
p "Daniel".my_attr

我的返回结果是 nil, 看了半天,不知道问题在哪?求助,谢谢。

@linuxgit

irb(main):042:0> p "Daniel".object_id  == "Daniel".object_id
false

如果换成

s = "Daniel"
s.my_attr = "ruby"
p s.my_attr

就是对的

附上链接:http://ruby-doc.org/core-2.2.2/Object.html#method-i-object_id

#1 楼 @ailen 谢谢 不是同一个 object 了 哈哈

3 楼 已删除
需要 登录 后方可回复, 如果你还没有账号请 注册新账号