【发布时间】:2016-03-25 00:41:05
【问题描述】:
我已经尝试通过#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
【问题讨论】:
-
您的问题令人困惑。你能提供一个你想要的输入和输出的例子吗?
-
为每个属性单独散列通常是不好的设计。另外,请使用
{ }而不是Hash.new,除非您需要指定默认值,例如Hash.new(0)。 -
输出 - people = [ { "first_name" => "Bob", "last_name" => "Jones", "age" => rand(1..100), "hobbies" => [“篮球”、“国际象棋”、“手机标签”] },