我有一个小程序打算在IRB中运行.它最终会输出看起来像数组的东西,虽然技术上不是数组.(该类继承自数组.)问题是,当我执行此类的实例时,例如example = Awesome.new(1,2,3),并且我写了"puts example",IRB的默认行为是将每个示例元素在它自己的行上.
而不是
[1,2,3]
Run Code Online (Sandbox Code Playgroud)
(这就是我想要的),IRB弹出这个.
1
2
3
Run Code Online (Sandbox Code Playgroud)
有没有一种聪明的方法来覆盖这个特殊类的puts方法?我尝试了这个,但它没有用.
def puts
self.to_a
end
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?
更新:所以我尝试了这个,但没有成功.
def to_s
return self
end
Run Code Online (Sandbox Code Playgroud)
因此,当我在IRB并且我只输入"示例"时,我得到了我正在寻找的行为(即[1,2,3].所以我想我可以回归自我,但我仍然在搞乱显然,某些东西.我不理解什么?
你应该覆盖to_s,它将自动处理,只需记住从中返回一个字符串to_s,它将作为一个魅力.
class Obj
def initialize(a,b)
@val1 = a
@val2 = b
end
def to_s
"val1: #@val1\n" +
"val2: #@val2\n"
end
end
puts Obj.new(123,321);
Run Code Online (Sandbox Code Playgroud)
val1: 123
val2: 321
Run Code Online (Sandbox Code Playgroud)
def puts(o)
if o.is_a? Array
super(o.to_s)
else
super(o)
end
end
puts [1,2,3] # => [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
或者只是使用p:
p [1, 2, 3] # => [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)