Ruby Tuesday – Array#*

Today’s Ruby Tuesday cover’s Array#*.

Array#* either takes a integer, N, as its argument, in which case it concatenates N copies of the array together and uses the result as it return value.

[1, 2, 3, 4, 5] * 3
% => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
["a", "b", "c"] * 4
% => ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c"]
[1, [:a, [:b, [:c]]]] * 2
% => [1, [:a, [:b, [:c]]], 1, [:a, [:b, [:c]]]]

Or it can take a string as its argument, in which case, it returns a flattened join of the items in the array with the string argument as the separator.

["a", "b", "c"] * ","
% => "a,b,c"
["a", "b", "c"] * "at"
% => "aatbatc"
[1, 2, 3, 4, 5] * ''
% => "12345"
[:x, :y, :z] * ';'
% => "x;y;z"
[[:a, 1], [:b, 2], [:c, 3]] * ';'
% => "a;1;b;2;c;3"
[1, [:a, [:b, [:c]]]] * ';'
% => "1;a;b;c"

Notice how multiplying by a string returns a flattened array joined together, instead of just the top level elements of an array with to_s called on them joined together.

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *