RSS
 

String Multiplication in Ruby

19 Sep

This is pretty interesting. In ruby you can multiply a string. So if you wanted you could write

puts ‘Repeat ‘ * 3

Which outputs:

Repeat Repeat Repeat

I like this and I do think it makes sense.  It does not work if you write

puts 3 * ‘Repeat ‘

Which I think is wrong because multiplication should be commutative.

 

Now doing this has somewhat caused a problem for concatenation though.  By multiplying string it is not clear what should happen when you do this.

puts ‘Repeat ‘ + 3

So ruby outputs an error, something that I’ve enjoyed recently in .NET has been that if you add or concatenate a string with another object the other object is automatically changed to a string, using the ToString method I believe. 

I would think that this is a much more common scenario than multiplying strings and therefore a bigger loss to productivity and readability of code.

 
No Comments

Posted in Web/Tech

 

Tags: