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

LinuxGit · April 21, 2015 · Last by linuxgit replied at April 21, 2015 · 1862 hits

元编程第 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 了 哈哈

2 Floor has deleted
You need to Sign in before reply, if you don't have an account, please Sign up first.