Arrays 有条件地遍历数组

Arrays 有条件地遍历数组,arrays,ruby,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 se

我想把一个数组分解成一个数组

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
def迭代数组(ary)
温度=[]
最终结果=[]
idx=0
温度单位推送单位[idx]
idx+=1
done=ary.length-1

当idx基于你函数给我的输出时,使用
%w(101这是第一个标签102这是第二个标签103这是第三个标签104这是第四个标签)。每个{x |放置x}
或使用
map
我得到相同的结果。如果您可以发布预期的输出,这将有所帮助。

这将在数组中一次迭代两个元素,并在右侧为数字时(或在写入时,在右侧不包含任何非数字字符时)对其进行“断开”(切片)。希望这有帮助

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

我会在
之前使用
可枚举#切片_:

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"]

您好,M,如果您能包含预期的输出,这将有助于清理一些格式错误。对不起,各位。我只是想了解一下格式。希望我能把它清理干净(在Vlad的帮助下)——这是正则表达式的一个很好的用法。但这是假设数组在其数值为。尽管如此,答案还是不错的+1谢谢你,弗拉德。它对输入做出了一些强有力的假设,但我只能利用原始问题中的任何可用信息!谢谢,mwp。我想我太依赖ruby-doc.org上的基本数组类文档了。我在ruby-lang.org上找到了关于#slice_when和#slice_between的信息。但我很困惑:当我输入Array.methods时,不应该切片_吗?什么时候,哪个数组应该继承自Enumerable?它不…尝试
Array.instance\u方法
:-)很好!我更喜欢这个,而不喜欢吃切片。slice\u before可以接受一个模式参数,因此可以将其简化为
字。slice\u before(/\d/)
。Thx muda。使用正则表达式有很长的路要走。不过,我不明白你的意思。
▶ 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"
# ]