Joining Arrays in Ruby
August 5, 2021 in ruby

While reading one of the old blog posts from the Riding Rails weblog, I came across a nifty way to join the values in an array.

Typically, you’d do this to join arrays:

> %w(1 2 3).join(", ")
=> "1, 2, 3"

However, multiplying an array with a separator accomplishes the same.

> %w(a b c d e) * "-"
=> "a-b-c-d-e"

> %w(a b c d e) * ", "
=> "a, b, c, d, e"

Is it concise? Definitely. Readable and expressive? I am not sure. However, it rhymes with the Ruby way of giving the programmer freedom to choose.