如何使用ruby

时间:2016-01-14 00:06:12

标签: arrays ruby hash nested

results = [
   {"day"=>"2012-08-15", "name"=>"John", "calls"=>"5"},
   {"day"=>"2012-08-15", "name"=>"Bill", "calls"=>"8"},
   {"day"=>"2012-08-16", "name"=>"Bill", "calls"=>"11"},
]

我可以使用以下代码访问哈希

results.find {|i| i["day"] == "2012-08-15" and i["name"] == "Bill"}["calls"]

如何通过以下代码访问电子邮件

results = [
   {"name"=>"John", "address"=>{"email"=> "john@example.com"}},
   {"name"=>"Bill", "address"=>{"email"=> "bill@example.com"}},
]

3 个答案:

答案 0 :(得分:3)

访问John的电子邮件:

results[0]["address"]["email"]
=> "john@example.com"

打印所有电子邮件:

results.each do |result|
  p result["address"]["email"]
end

答案 1 :(得分:1)

results.find {|i| i["name"] == "Bill"}["address"]["email"]

虽然你应该验证结果不是null。

请参阅此fiddle

答案 2 :(得分:0)

如果

results = [
   {"name"=>"Irma", "address"=>{"email"=> "irma@example.com"}},
   {"name"=>"John", "address"=>{"email"=> "john@example.com"}},
   {"name"=>"Bill", "address"=>{"email"=> "bill@example.com"}},
]

你希望今天能收到John的电子邮件地址,也许明天可能是Irma,你可能想要创建一个新的哈希:

addresses = results.map { |h| [h["name"], h["address"]["email"]] }.to_h
  #=> {"Irma"=>"irma@example.com", "John"=>"john@example.com", "Bill"=>"bill@example.com"}