2017-01-22 82 views
3
groceries=[{"bread"=>"2", "eggs"=>"3", "cheese"=>"1", "butter"=>"4"}, 
      {"juice"=>"3", "milk"=>"1", "tea"=>"1", "sugar"=>"1"}] 

如何迭代每個散列並將其推入單獨的數組? 我想要的東西,看起來像這樣:通過ruby中的多維哈希進行迭代

items = [["bread","eggs","cheese","butter"],["juice","milk","tea","sugar"]] 
+0

如果我想保留格式但只返回長度大於五的元素,該怎麼辦? – olafsadventures

+0

你的意思是,密鑰超過5個字符? –

回答

2

試試這個

groceries.map(&:keys) 
=> [["bread", "eggs", "cheese", "butter"], ["juice", "milk", "tea", "sugar"]] 
1

如果你只是想有5個或更多字符的按鍵:

p groceries.map{ |hash| hash.keys.select{ |key| key.length >= 5 } } 
#=> [["bread", "cheese", "butter"], ["juice", "sugar"]] 

如果您只需要最多2個具有5個或更多字符的鍵:

p groceries.map{ |hash| hash.keys.select{ |key| key.length >= 5 }.first(2) } 
#=> [["bread", "cheese"], ["juice", "sugar"]] 
+0

如果我只想從每個包含五個或更多字符的散列中選擇前兩個,該怎麼辦? [[「麪包」,「奶酪」],[「果汁」,「牛奶」]] – olafsadventures

+0

謝謝,這非常有幫助。 – olafsadventures

+0

猜猜你也可以使用'.grep(/...../)'來選擇長度爲5或更長的鍵。 – akuhn