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 have a typo in your latter snippet: it should start with
x = 6(without quotes.)Everything in Ruby is an object, including instances of
String,Integer, evennilwhich is [the only] instance ofNilClass.That said, there is no just an operator
*. It’s a plain old good method, declared on different classes, that is called by the operator*(thanks @SergioTulentsev for picky wording comment.) Here is a doc forString#*, other you might find yourself. And"a" * 6is nothing else, than:You might check the above in your console: it’s a perfectly valid Ruby code. So, different classes have different implementations of
*method, hence the different results above.