你可以使用slice_before
:
a = [1,'hi','what',2,'how','where',3,'one',4,'two','three','four',5,'five','six']
p a.slice_before(Integer).map{ |int, *words| { int => words } }
#=> [{1=>["hi", "what"]}, {2=>["how", "where"]}, {3=>["one"]}, {4=>["two", "three", "four"]}, {5=>["five", "six"]}]
注意,對於不同的鍵散列的陣列可以在一個單一的哈希凝結:
a.slice_before(Integer).map{ |int, *words| [int, words] }.to_h
#=> {1=>["hi", "what"], 2=>["how", "where"], 3=>["one"], 4=>["two", "three", "four"], 5=>["five", "six"]}
更新:
如果你的密鑰串看起來像一個數字,你可以嘗試:
a = ["1",'hi','what',"2",'how','where',"3",'one',"4",'two','three','four',"5",'five','six']
a.slice_before(/^\-?\d+$/).map{ |int, *words| [int.to_i, words] }.to_h
#=> {1=>["hi", "what"], 2=>["how", "where"], 3=>["one"], 4=>["two", "three", "four"], 5=>["five", "six"]}
請閱讀「[問]」,並以「[MCVE]」沿着鏈接的網頁。你給我們的輸入數據和預期的輸出,基本要求,但是你有沒有向顯示解決問題,這是至關重要的任何努力。你嘗試了什麼,爲什麼它沒有工作? –