2017-03-03 21 views
-1
a=[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','thre‌​e','four',"5",'five'‌​,'six'] 

我需要創建哈希的陣列狀

a=[{1=>['hi','what']},{2=>['how','where']},{3=>['one']},{4=>['two','three','four']},{5=>['five','six']}] 

我可以使用任何預定義的功能來實現這一?

+1

請閱讀「[問]」,並以「[MCVE]」沿着鏈接的網頁。你給我們的輸入數據和預期的輸出,基本要求,但是你有沒有向顯示解決問題,這是至關重要的任何努力。你嘗試了什麼,爲什麼它沒有工作? –

回答

2

你可以使用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"]} 
+0

我正要張貼內容幾乎相同的:) –

+0

嗨,這是絕對回答我的問題,但我想對於另一種可能性的答案,以及爲例,如果陣列是一個'=「1」,「喜」,」什麼」, 「2」, '如何', '地點', 「3」, '一', 「4」, '兩節', '三', '四', 「5」, '十二五', '六' ]有什麼辦法可以在數字下分組嗎? – RAJ

+0

@RAJ:答案更新 –

相關問題