通过数组有条件地迭代
我想将一个数组分解为一个数组数组。通过数组有条件地迭代
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
我认为必须有一个更简单,更优雅的方式。有任何想法吗?
根据您的函数给出的输出结果,使用%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
我得到了相同的结果。如果您可以发布您的预期输出,这将有所帮助。
这将一次遍历数组中的两个元素,当右侧是一个数字时“断开”(切片)它(或者当它被写入时,当右侧不包含任何非零元素时)数字字符)。希望这可以帮助!
test_ary.slice_when { |_, r| r !~ /\D/ }.map { |w| w.join(' ') }
我会用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"
# ]
Thx muda。使用正则表达式有很长的路要走 –
欢迎erel,但我无法理解你的意思。 – mudasobwa
中号嗨,这将帮助你将包括预期的输出,这将有助于清理一些格式错误。 – mwp
对不起。我只是着手格式化。希望我把它清理干净(在Vlad的帮助下) - M –