How to join some (not all) array elements based on condition in ruby?

arrays, ruby, string

Solution

array.slice_before{|s| !s.start_with?("(")}.map{|a| a.join(" ")}
# => ["foo (bar)", "baaz", "quux", "herp (derp)"]

Problem

Say I have an array of strings like this: ``` array = ["foo", "(bar)", "baaz", "quux", "herp", "(derp)"] ``` And I need to join items starting with "(" with the previous item to get output like this: ``` ["foo (bar)", "baaz", "quux", "herp (derp)"] ``` I guess it has to be something like get indices of array items that match `/^\(/` and then iterate over original array in a block, joining items at `index-1..index`, and deleting at `index`

Original source