修改属于扩展类的对象的默认返回值 [英] Modifying the default return value of an object belonging to an extended class
问题描述
我是rails语法相对较新。我有一个LogString类
class LogString<数组
我用它做下面的操作
logs = LogString.new
pre>
logs.push'this happened'
logs.push'发生'
这很好。我想只能写入
logs
返回logs.join('|')
,所以我在寻找一个语法方法log_string here
class LogString<数组
def log_string
self.join('|')
end
end
但是当我简单地写类实例名称时,log_string会自动调用:logs
我该怎么办?
解决方案你不能仅仅引用一个对象,并让它在对象上调用一个方法,但是你可以非常接近。
如果您重写
to_s
方法(到字符串的缩写),您将能够class LogString<数组
def to_s
self.join'| '
end
end
log = LogString.new
log< message one
log<< message two
puts#{log}
I am relatively new to the rails syntax. I have a LogString class
class LogString < Array
I do the following with it
logs = LogString.new logs.push 'this happened' logs.push 'that happened'
which works fine. i want to be able to just write only
logs
to return what would be logs.join( ' | ' )
so i am looking for a syntax something like the method log_string here
class LogString < Array def log_string self.join( ' | ' ) end end
but where log_string is automatically called when i simply write the class instance name: logs
how can i do that?
解决方案You can't just reference an object and have it call a method on the object, but you can get pretty close.
If you override the
to_s
method (short for "to string"), you'll be able to do something like...class LogString < Array def to_s self.join ' | ' end end log = LogString.new log << "message one" log << "message two" puts "#{log}"
这篇关于修改属于扩展类的对象的默认返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!