Order Matters! 2

Posted by Matt Williams

The order in which operations occur can often make a difference in Ruby:
1
2
3
4
5
6
7
8
9

$ irb
>> 5 * "a"
TypeError: String can't be coerced into Fixnum
  from (irb):1:in `*'
  from (irb):1
>> "a" * 5
=> "aaaaa"
>> 

The reason is quite simple — everything in Ruby is an object. The '*' behaves differently when applied to different objects (and, in fact, can be overridden). So, because the '*' method as implemented for Fixnum expects a number as its argument, and a String isn't a number, it complains. By the same token, the behaviour of '*' for String is for the string to repeat itself as many times as the argument specifies, it works.