初始化值
问题描述:
如何我可以做这样的事情:初始化值
class Some < String
def m1(a, b)
self = a + b
end
end
s = Some.new("hello")
s.m1("one ", "two")
p s # => "one two"
答
这取决于你如何定义究竟“像”。
如果您希望使所有指向给定Some
对象的变量现在指向a + b
的结果字符串,那是不可能的。
如果要更改给定的Some
对象的字符串内容,可以使用replace
方法,即replace(a+b)
。
为了说明差异使用replace
和再分配之间:
class Some < String
def m1(a, b)
replace(a + b)
end
end
s1 = Some.new("hello")
p s1.object_id # some number
s1.m1("one ", "two")
p s1 # "one two"
p s1.object_id # the same number as above
p s1.class # Some
s2 = Some.new("hello")
p s2.object_id # some number
s2 = "one " + "two"
p s2 # "one two"
p s2.object_id # a different number
p s2.class # String
后者行为无法实现使用的方法。
答
像这样的事情?:
class Some < String
def m1(a, b)
self.clear << a << b
end
end
some = Some.new("bye")
some.m1("hello ","world")
p some #=>hello world
答
红宝石非标准库对于这个情况,有delegate
。您可以安全地覆盖标准课程 。建议在 破坏性方法名称中使用!
。
require 'delegate'
class MyStr < DelegateClass(String)
def initialize dnm=""
@str = dnm
super(@str)
end
def m1!(a,b)
@str.replace(a + b)
end
end
s = MyStr.new("deneme")
s.m1!("de", "ne")
我已经更新了我的问题来说明使用'replace'当我想 – demas 2012-03-07 12:23:39
@demas你会得到输出。问题是你是否只想改变's'指向的'Some'对象的内容(或者你希望'''实际指向别的地方(即和你一样的行为) =“one”+“two”'后者是不可能的 – sepp2k 2012-03-07 12:26:20
它工作正常,但我在寻找更通用的解决方案,例如,我需要解决某些
demas
2012-03-07 12:33:13