Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does array * string mean in Ruby?

I was looking through some Rails source code and came across

# File vendor/rails/activesupport/lib/active_support/vendor/builder-2.1.2/builder/css.rb, line 129
129:     def target!
130:       @target * ''
131:     end

What does the * '' do? Is that multiplication by an empty string...? And why would you do that.

like image 423
Aaron Yodaiken Avatar asked Feb 10 '10 00:02

Aaron Yodaiken


4 Answers

This is a bizarre syntax. These are equivalent:

>> [1, 2, 3] * 'joiner'
=> "1joiner2joiner3"

>> [1, 2, 3].join 'joiner'
=> "1joiner2joiner3"

so in this case it joins all the entries of @target into one string, with nothing between the entries.

Note: if you do something like [1, 2, 3] * 3 (using an int instead of a str), you'll get three concatenated copies of the array instead.

like image 82
Peter Avatar answered Nov 11 '22 01:11

Peter


It does the same thing as:

["foo","bar","baz"].join

http://ruby-doc.org/core/classes/Array.html#M002210

Per Z.E.D.'s suggestion, you would use it if you want to confuse people and make your code more error prone.

like image 43
klochner Avatar answered Nov 11 '22 02:11

klochner


Really cryptic code indeed.

After checking the source code, I realized that @target is actually an Array instance, I know you can do stuff like this

[5] * 5 # => [5,5,5,5,5]

I don't know where Array#* is defined (maybe in ActiveSupport), but what I can tell you is that, this is the behaviour when it gets multiplied by a String

[1,2,3] * 'comma' # => "1comma2comma3"
[1,2,3] * '' # => '123'

So I can infer it is concatanating all the elements of the array without any separators.

like image 4
Roman Gonzalez Avatar answered Nov 11 '22 00:11

Roman Gonzalez


Array#* with a String argument is equivalent to Array#join.

like image 2
Jörg W Mittag Avatar answered Nov 11 '22 01:11

Jörg W Mittag