【发布时间】:2012-03-01 21:51:27
【问题描述】:
当我使用 puts 时,我重写了 to_s 方法以获得漂亮的输出,但同时我似乎失去了检查对象的能力。有没有办法在覆盖 to_s 时获得检查的正常输出?
class Person
attr_accessor :first, :last, :birthdate
def initialize(first=nil, last=nil, birthdate=nil)
@first, @last, @birthdate = first, last, birthdate
end
def age
if birthdate
Time.now.year-birthdate
else
0
end
end
def to_s
"#{@first} #{@last} (#{age})"
end
end
me = Person.new("Peter", "Marien", 1962)
p me >>Peter Marien (50)
p me.inspect >>"Peter Marien (50)"
#Need #<Person:0x1ec2550 @first="Peter", @last="Marien", @birthdate=1962>
【问题讨论】:
-
这个错误报告讨论了同样的问题:bugs.ruby-lang.org/issues/4453 但是我没有看到票证有任何进展。
-
所以这是一个错误,没有意识到..,感谢链接
标签: ruby oop overriding