This post originated from an RSS feed registered with Ruby Buzz
by Matt Williams.
Original Post: Order Matters!
Feed Title: Ruby Blender
Feed URL: http://feeds2.feedburner.com/RubyBlender
Feed Description: This blog contains short-ish ruby tips, hints, and techniques.
The order in which operations occur can often make a difference in Ruby:
123456789
$ 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.