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.
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.
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.
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.
Array#* with a String argument is equivalent to Array#join.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With