【问题标题】:Adding hashes to hashes (Ruby)将散列添加到散列(Ruby)
【发布时间】: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" => [“篮球”、“国际象棋”、“手机标签”] },

标签: ruby hash


【解决方案1】:

假设这是您的结构,您可以这样做:

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。您应该对像这样的常规结构使用符号,对更多任意数据使用字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多