通过数组有条件地迭代

时间:2016-08-03 03:59:09

标签: arrays ruby

我想将数组分成数组数组。

test_ary = %w(101 This is the first label 102 This is the second label 103 This is
the third label 104 This is the fourth label)

result = iterate_array(test_ary)

预期产出:

#⇒ [
#    "101 This is the first label",
#    "102 This is the second label",
#    "103 This is the third label",
#    "104 This is the fourth label" ]

我写了以下方法:

def iterate_array(ary)
  temp_ary = []
  final_ary =[]
  idx = 0
    temp_ary.push ary[idx]
    idx +=1
    done = ary.length - 1
    while idx <= done
        if ary[idx] =~ /\d/
            final_ary.push temp_ary
            temp_ary = []
            temp_ary.push ary[idx]
        else
            temp_ary.push ary[idx]
        end
        idx +=1
    end
    final_ary.push temp_ary
    returned_ary=final_ary.map {|nested_ary| nested_ary.join(" ")}
    returned_ary
end

我认为必须有一种更简单,更优雅的方式。有什么想法吗?

4 个答案:

答案 0 :(得分:3)

我会使用Enumerable#slice_before

test_ary.slice_before { |w| w =~ /\d/ }.map { |ws| ws.join(" ") }
# => ["101 This is the first label", "102 This is the second label", "103 This is the third label", "104 This is the fourth label"]

编辑:正如@mwp所说,你可以做得更短:

test_ary.slice_before(/\d/).map { |ws| ws.join(" ") }
# => ["101 This is the first label", "102 This is the second label", "103 This is the third label", "104 This is the fourth label"]

答案 1 :(得分:2)

▶ test_ary.join(' ').split(/ (?=\d)/)
#⇒ [
#  [0] "101 This is the first label",
#  [1] "102 This is the second label",
#  [2] "103 This is the third label",
#  [3] "104 This is the fourth label"
# ]

答案 2 :(得分:1)

这将一次遍历数组中的两个元素并且&#34; break&#34; (切片)当右侧是数字时(或者当它的右侧不包含任何非数字字符时)。希望这有帮助!

test_ary.slice_when { |_, r| r !~ /\D/ }.map { |w| w.join(' ') }

答案 3 :(得分:0)

根据您的函数给出的输出%w(101 This is the first label 102 This is the second label 103 This is the third label 104 This is the fourth label).each { |x| puts x }或使用map,我得到相同的结果。如果您可以发布预期的输出,这将有所帮助。

相关问题