bill bill - 7 months ago 25
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"


String can't be coerced into Fixnum

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?


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")


"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.