假设我有一个这样的字符串数组:
array = ["foo", "(bar)", "baaz", "quux", "herp", "(derp)"]
我需要将以“(”开头的项目与前一个项目连接起来,以获得如下输出:
["foo (bar)", "baaz", "quux", "herp (derp)"]
我想它必须是类似于获取与 /^\(/
匹配的数组项的索引,然后迭代 block 中的原始数组,在 index-1 处连接项。 .index
,并在 index
最佳答案
array.slice_before{|s| !s.start_with?("(")}.map{|a| a.join(" ")}
# => ["foo (bar)", "baaz", "quux", "herp (derp)"]
关于ruby - 如何根据 ruby 中的条件加入一些(不是全部)数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24712309/