If x is a non-integer, I get this result:
x = "a"
x * 6 #=> aaaaaa
6 * x #=> TypeError: String can't be coerced into Fixnum
whereas if x is an integer:
x = 6
x * 6 #=> 36
6 * x #=> 36
It's strange that the operand order in multiplication matters if x is a non-integer, and not if x is an integer. Can someone explain what the rational is behind this? When x is a string, why must variable x precede the * operator to avoid raising an error?
You need to understand what the method
*does.1. That depends on the method's receiver. For"cat".*(3),"cat"is*'s receiver. For1.*(3)(which, as explained later, can be written,1*3)1is*'s receiver. The term "receiver" derives from OOP's concept of sending a message (method) to a receiver.A method can be defined on an object (e.g.,
"cat"or1) in one of two ways. The most common is that the method is an instance method defined on the receiver's class (e.g.,*defined on"cat".class #=> Stringor1.class #=> Integer. The second way, which is not applicable here, is that the method has been defined on the object's singleton class, provided the object has one. ("cat"has a singleton class but1, being an immediate value, does not.)When we see
"cat".*(3), therefore, we look to the doc for String#* and conclude thatFor
1*(3), we look to Integer#*, which tells us thatLet's try another:
[1,2,3].*(3), Because[1,2,3].class #=> Arraywe look to Array#* and conclude thatNote that this method has two forms, depending on whether its argument is an integer (as here) or a string. In the latter case
Many methods have different behaviors that depend on its arguments (and on whether an optional block is provided).
Lastly, Ruby allows us to use a shorthand with these three methods (and certain others with names comprised of characters that are not letters, numbers or underscores.):
This shorthand is generally referred to as "syntactic sugar".
1 Ruby's method names are not restricted to words, such as "map", "upcase" and so on. "*", "~", "[]" and "[]=", for example, are valid method names"