sigleton class里怎样得到对象的值
str = "ABC"class << str
p self
end显示self是#<Class:#<String:0x15d4bb0>>这么样一个东西
我要想在class << str里得到str的值"ABC"怎么做呢? 得需要多写一点代码:def sync_singleton_value object
class << object
class << self
attr_accessor:special_value
end
def singleton_class
class << self;self;end
end
end
object.singleton_class.special_value = object
end
# 下面是用法
str = "ABC"
sync_singleton_value str
class << str
p special_value
end另外,在使用时,每次class << str之前,都需要先用sync_singleton_value方法来同步一下value,如上面的代码所示。 Ruby1.9下,singleton_class已经有了。所以就不用定义了,
def sync_singleton_value object
class << object
class << self
attr_accessor:special_value
end
end
object.singleton_class.special_value = object
end
# 下面是用法
str = "ABCD"
sync_singleton_value str
# special_value属性 和str引用的是同一个对象,所以用special_value属性就可
class << str
p special_value
end 又修改了一下,没有本质区别,用在Ruby1.9下
def sync_singleton_value object
object.singleton_class.singleton_class.instance_eval{ attr_accessor:special_value }
object.singleton_class.special_value = object
end
# 下面是用法
str = "ABCD"
sync_singleton_value(str)
class << str
p special_value
end
又找到一个方法,(Ruby1.9)
str = "ABCD"
str.singleton_class.instance_eval "@special_value = str"
#@special_value 和 str 引用的是同一个对象
class << str
p @special_value
end
Ruby1.8下得先实现一个singleton_class方法。 楼上玩杂耍啊? 回复 6# 2gua
哈哈,主要是楼主的问题挺有意思,就多捣鼓了几下。 鼓励楼上啊!
页:
[1]