散列哈希内部哈希数组

时间:2016-06-22 17:59:15

标签: arrays ruby hash

我有这样的哈希:

document = {
  "results" => {[
    {"ip" => 10, "host" => 12},
    {"ip" => 13, "host" => 17}
  ]}
}

这是一个哈希中包含哈希数组的项目哈希。我指定的值为ip = 10

如果ip超过10,我想用值打印两个键。这个哈希非常复杂,我不知道如何访问这些值。你能救我吗?

编辑: 如果我像这样哈希怎么办? document = { "results" => [{"ip" => 10, "host" => 12, "temp" => yes},{"ip" => 13, "host" => 17, "temp" => yes}] }并希望在将ip与10匹配后只打印ip和主机?

3 个答案:

答案 0 :(得分:1)

document["results"].each do |result|
  if result["ip"] > 10
    puts result # will print ip and host
  end
end

答案 1 :(得分:1)

我会使用select

document = { "results" => [{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}] }

puts document['results'].select { |hash| hash['ip'] > 10 }
#=> {"ip"=>13, "host"=>17}

说明:

document['results']

返回哈希数组:

[{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}]

在下一步中,在返回的数组上调用select

document['results'].select { |hash| hash['ip'] > 10 }

这将返回分配给键> 10的值为'ip'的所有子哈希值。

puts只会将结果打印到STDOUT

答案 2 :(得分:0)

我今天有另一个问题。这是我的代码:

require 'rubygems'
require 'json'

document = JSON.load File.new("hosts.txt")
file = JSON.load File.new("admins.txt")

first_table = document["results"]
second_table = file["admins"]
new_one = first_table | second_table

第一个哈希看起来像这样:

document = { "results" => [{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}] }

第二个哈希是

file = { "admins" => [{"host" => 12, "name" => 12},{"host" => 17, "name" => 17}] }

我希望将这两个哈希值与主机匹配,并使用相同的值来获取

{ "new_one" => [{"ip" => 10, "host" => 12, "name" => 12}, {"ip" => 13, "host" => 17}, "name" => 17]

当我尝试new_one = first_table | second_table时,它说test.rb:24:<main>': undefined method |&#39;对于#Hash:0x00000002ca8be8(NoMethodError),当我尝试new_one = first_table.merge(second_table)时,它说test.rb:26:在<main>': undefined method合并&#39;对于#Array:0x00000002ce88b0(NoMethodError)。那么这些哈希有什么问题呢?有一次它们是哈希,第二次是阵列?如何加工这些哈希?两个哈希中主机的键和值相同。