Ruby:叫什么方法?
假设我有一个 MyClass
的对象 x
。当我 puts x
时,会调用什么方法?我需要用我自己的覆盖它。
我以为它是 .inspect
,但不知何故重写的 inspect
没有被调用。
例如,我有一个类 Sum
:
class Sum
initiazlie a, b
@x = a + b
end
end
我想像这样访问结果:
s = Sum.new(3,4)
puts s #=> 7 How do I do this?
puts 10 + s #=> 17 or even this...?
Assume, I have an object x
of MyClass
. What method is called, when I do puts x
? I need to override it with my own one.
I thought it was .inspect
, but somehow overridden inspect
isn't being called.
For example, I have a class Sum
:
class Sum
initiazlie a, b
@x = a + b
end
end
And I wanna access the result like this:
s = Sum.new(3,4)
puts s #=> 7 How do I do this?
puts 10 + s #=> 17 or even this...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它调用:
to_s
或者,如果您愿意,您可以从
to_s
调用inspect
,以便获得对象的一致字符串表示形式。It calls:
to_s
Or if you want, you can just call
inspect
fromto_s
, so that you have a consistent string representation of your object.首先,您的 Sum 类无效。定义应该是。
默认情况下,为获取人类可读表示而调用的方法是检查。在 irb 中尝试此操作
,但在您的情况下,您使用强制字符串转换的 puts 方法。因此,首先使用
to_s
方法将Sum
对象转换为字符串。另请注意,您的最后一个示例属于第三种情况。因为您对 Fixnum + 另一个对象求和,所以结果预计是一个 Fixnum,并且调用的方法是
to_s
,但是是在 Fixnum 类中定义的方法。为了使用 Sum 类中的项,您需要切换 sum 中的项目并在对象中定义
+
。First, your Sum class is invalid. The definition should be.
By default, the method called to get a human readable representation is inspect. Try this in
irb
But in your case, you use the
puts
method which forces a string conversion. For this reason, theSum
object is first converted to string using theto_s
method.Also note your last example fall into a third case. Because you sum a Fixnum + an other object, the result is expected to be a Fixnum and the method called is
to_s
but the one defined in the Fixnum class.In order to use the one in your Sum class, you need to switch the items in the sum and define the
+
in your object.