Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't `"repeat" * 3` the same as `3 * "repeat"` in Ruby?

When I type this:

puts 'repeat' * 3

I get:

>> repeat repeat repeat

But it's not working if I do this:

puts 3 * 'repeat'

Why?

like image 979
levirg Avatar asked Mar 30 '10 06:03

levirg


1 Answers

In Ruby, when you call a * b, you're actually calling a method called * on a. Try this, for example:

a = 5
=> 5
b = 6
=> 6
a.*(b)
=> 30

c = "hello"
=> "hello"
c.*(a)
=> "hellohellohellohellohello"

Thus <String> * <Fixnum> works fine, because the * method on String understands how to handle integers. It responds by concatenating a number of copies of itself together.

But when you do 3 * "repeat", it's invoking * on Fixnum with a String argument. That doesn't work, because Fixnum's * method expects to see another numeric type.

like image 50
John Feminella Avatar answered Sep 19 '22 00:09

John Feminella