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.

Comments

Leave a response

  1. raggiApril 09, 2008 @ 10:31 AM
    I would stress that you probably want to move away from the ideas of BODMAS, etc. This is not a mathematical expression, it's a method call, with nice syntax. Clearly you know this, but I think confusing these things with operators should be avoided at all times, as it will eventually lead to a better understanding thinking about objects and methods as they are.
  2. Matt WilliamsApril 09, 2008 @ 05:25 PM
    You're right, I could have phrased it better -- it is a method call, and I guess I was explaining in terms of most languages, where it is an operator -- that's how most people would recognize the *. But you are certainly correct that it is a method with syntactic sugar.
Comment