misterinevitable

Array#join flattens nested arrays

Suppose you have a nested array like this…

[1, [2, 3, [4], 5]]

… and you want to convert it into the string "1, 2, 3, 4, 5".

Before I read the documentation for Array#join, I would have thought I needed to #flatten the array before I #joined it:

[1, [2, 3, [4], 5]].flatten.join(', ') # "1, 2, 3, 4, 5"

It turns out Array#join recursively calls Array#join on nested arrays, so you don’t need to explicitly #flatten it. This works:

[1, [2, 3, [4], 5]].join(', ') # "1, 2, 3, 4, 5"