为什么不是`“重复” * 3`一样`3 *“重复”`在Ruby中?
-
23-09-2019 - |
题
当我输入:
puts 'repeat' * 3
我得到:
>> repeat repeat repeat
但它不工作,如果我这样做:
puts 3 * 'repeat'
为什么?
解决方案
在Ruby中,当你调用a * b
,你实际上调用呼吁*
a
方法。尝试此,例如:
a = 5
=> 5
b = 6
=> 6
a.*(b)
=> 30
c = "hello"
=> "hello"
c.*(a)
=> "hellohellohellohellohello"
因此<String> * <Fixnum>
工作得很好,因为在*
的String
方法了解如何处理整数。它通过连接若干本身拷贝一起进行响应。
但是,当你这样做3 * "repeat"
,它调用*
上Fixnum
与String
说法。不工作,因为Fixnum
的*
方法期望看到另一个数值类型。
不隶属于 StackOverflow