我想把一个数组分解成一个数组。
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
我认为一定有一种更简单、更优雅的方式。有什么想法吗?
我会使用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"]
▶ 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"
# ]
这将一次遍历数组的两个元素,并在右侧为数字时(或在写入时,当右侧不包含任何非数字字符时)"打断"(切片)它。希望这能有所帮助!
test_ary.slice_when { |_, r| r !~ /D/ }.map { |w| w.join(' ') }
根据函数给我的输出,使用%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
,我会得到相同的结果。如果你能发布你期望的输出,那会很有帮助。