我想將一個數組分解爲一個數組數組。通過數組有條件地迭代
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
我認爲必須有一個更簡單,更優雅的方式。有任何想法嗎?
中號嗨,這將幫助你將包括預期的輸出,這將有助於清理一些格式錯誤。 – mwp
對不起。我只是着手格式化。希望我把它清理乾淨(在Vlad的幫助下) - M –