o = Object.new
o.instance_eval { @str = "foo" }
p o # => #<Object:0x5dd1a0 @foo="bar">
這很好。以對象作爲參數調用p
會打印對象inspect
方法的輸出。但不幸的是,如果對象有一個to_s
方法,然後重寫它的輸出,輸出:仿真默認對象#inspect輸出?
class << o
def to_s; @str; end
end
p o.to_s # => "foo"
p o # => foo
因此,要解決這個問題,我們有我們的對象定義inspect
方法:
class << o
def inspect; "blah"; end
end
p o # => "blah"
如何讓我的對象的inspect
方法輸出默認的Ruby方式,如我的第一個代碼示例的第3行所示?
我最接近的是下面的,但我不知道這是否是完全正確
class << o
def inspect
vars = instance_variables.collect { |v| v.to_s << "=#{instance_variable_get(v).inspect}"}.join(", ")
"#<#{self.class}:0x#{object_id} #{vars}>"
end
end
您使用的是什麼版本的Ruby? – 2011-04-24 15:32:52