8

当我输入这个:

puts 'repeat' * 3

我得到:

>> repeat repeat repeat

但如果我这样做,它就不起作用:

puts 3 * 'repeat'

为什么?

4

1 回答 1

28

在 Ruby 中,当您调用 时a * b,实际上是在调用一个名为*on的方法a。试试这个,例如:

a = 5
=> 5
b = 6
=> 6
a.*(b)
=> 30

c = "hello"
=> "hello"
c.*(a)
=> "hellohellohellohellohello"

因此<String> * <Fixnum>可以正常工作,因为*on 方法String了解如何处理整数。它通过将自身的多个副本连接在一起来响应。

但是当你这样做时,3 * "repeat"它会调用一个参数。那是行不通的,因为's方法期望看到另一种数字类型。*FixnumStringFixnum*

于 2010-03-30T07:07:56.483 回答