bill bill - 3 months ago 10
Ruby Question

Multiplying string by integer vs integer by string in ruby

I was playing around in irb, and noticed one cannot do

5 * "Hello"
.

Error


String can't be coerced into Fixnum


However
"Hello"*5
provided
"HelloHelloHelloHelloHello"
as expected.

What is the exact reason for this? I've been looking around in the doc's and could not find the exact reason for this behavior. Is this something the designers of ruby decided?

Answer

This is because that operators are also methods(Well there are exceptions as Cary has listed in the comments which I wasn't aware of).

For example

array << 4    ==   array.<<4
array[2]      ==   array.[](2)
array[2] ='x' ==   array.[] =(2,'x')

In your example:

5 * "Hello" => 5.*("Hello")

Meanwhile

"hello" *5 => 5.*("hello")

An integer cannot take that method with a string param

If you ever dabble around in python try 5*hello and hello*5, both work. Pretty interesting that ruby has this feature to be honest.