2016-03-25 186 views
0

我試着通過#Hash.new添加散列沒有成功,現在我正在嘗試.merge按照有限的成功論壇。我正在嘗試將#rand(1..100)添加到[0]中,而無需手動進入哈希。有任何想法嗎?添加散列到散列(紅寶石)

#age = Hash.new 
#email = Hash.new 
#age2 = rand(1..100) 
people = [ 
{ 
"first_name" => "Bob", 
"last_name" => "Jones", 
"hobbies" => ["basketball", "chess", "phone tag"] 
}, 
{ 
"first_name" => "Molly", 
"last_name" => "Barker", 
"hobbies" => ["programming", "reading", "jogging"] 
}, 
{ 
"first_name" => "Kelly", 
"last_name" => "Miller", 
"hobbies" => ["cricket", "baking", "stamp collecting"] 
} 
] 

people[0].each do |w| 
people.merge({:age => rand(1..100)}) 
puts "array 0 is #{w}" 
end 

puts p people 
+0

你的問題很混亂。你能提供一個你想要的輸入和輸出的例子嗎? – Shelvacu

+0

爲每個屬性分散散列通常是不好的設計。另外,除非需要指定默認值,如'Hash.new(0)',否則使用'{}'而不是'Hash.new'。 – tadman

+0

輸出 - 人= [{ 「first_name的」=> 「鮑勃」, 「姓氏」=> 「瓊斯」, 「年齡」=>蘭特(1..100), 「愛好」=> [「籃球」,「國際象棋」,「電話標籤」] }, – whatabout11

回答

2

假設這是您的結構,你這樣做:

people.each do |person| 
    person['age'] = rand(1..100) 
end 

你最好要使用符號式按鍵來代替。這將意味着他們宣稱這樣的:

people = [ 
    { 
    first_name: "Bob", 
    last_name: "Jones", 
    ... 
    }, 
    ... 
] 

這樣,你訪問他們喜歡people[0][:first_name]。您在哈希中合併使用:age的符號密鑰。請記住,Ruby中的字符串和符號並不等同,即'bob' != :bob。您應該使用這樣的常規結構的符號,更多任意數據的字符串。

+0

很好的答案和簡單,謝謝! – whatabout11