8

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?

John Feminella
  • 303,634
  • 46
  • 339
  • 357
levirg
  • 1,033
  • 2
  • 8
  • 9
  • 3
    It's a leaky abstraction. http://www.joelonsoftware.com/articles/LeakyAbstractions.html – Levi Mar 30 '10 at 09:37
  • 5
    i'd argue its not a leaky abstraction, there is no reason to assume that * is commutative for string and fixnum. – jk. Mar 30 '10 at 12:34

1 Answers1

28

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.

John Feminella
  • 303,634
  • 46
  • 339
  • 357