为什么不重复"重复"*3`与Ruby中的`3*"重复"`相同?

lev*_*irg 8 ruby methods operators associativity

当我输入这个:

puts 'repeat' * 3
Run Code Online (Sandbox Code Playgroud)

我明白了:

>> repeat repeat repeat
Run Code Online (Sandbox Code Playgroud)

但如果我这样做,它就无法运作:

puts 3 * 'repeat'
Run Code Online (Sandbox Code Playgroud)

为什么?

Joh*_*lla 28

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

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

c = "hello"
=> "hello"
c.*(a)
=> "hellohellohellohellohello"
Run Code Online (Sandbox Code Playgroud)

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

但是,当你这样做3 * "repeat",它的调用*FixnumString争论.这不起作用,因为Fixnum's *方法希望看到另一种数字类型.