新的哈希键具有空值[关闭]

问题描述 投票:-1回答:1

如预期了以下工作:

require 'json'

hash = {}
hash['some_key'] = false
hash['another_key'] = "that"
hash['my_key'] = hash.delete('some_key')
puts hash.to_json

结果

{"another_key":"that","my_key":false}

但是,当我尝试以下方法,它导致对于新键,一个空值。此外,旧的密钥没有被删除:

require 'whois-parser'
require 'json'

c = Whois::Client.new
record = c.lookup('google.com')
parser = record.parser

msg = {}
for prop in Whois::Parser::PROPERTIES
  msg[prop] = parser.send(prop)
end

msg['available'] = msg.delete('available?')
puts msg.to_json

结果:

{
  "disclaimer":"TERMS OF USE: ...",
  "domain":"google.com",
  "domain_id":"2138514_DOMAIN_COM-VRSN",
  "status":"registered",
  "available?":false,
  "registered?":true,
  "created_on":"1997-09-15 00:00:00 -0700",
  "updated_on":"2018-02-21 10:45:07 -0800",
  "expires_on":"2020-09-13 21:00:00 -0700",
  "registrar":"#<struct Whois::Parser::Registrar id=\"292\", name=\"MarkMonitor, Inc.\", organization=\"MarkMonitor, Inc.\", url=\"http://www.markmonitor.com\">",
  "registrant_contacts":[],
  "admin_contacts":[],
  "technical_contacts":[],
  "nameservers":["ns2.google.com","ns1.google.com","ns4.google.com","ns3.google.com"],
  "available":null
}

为什么关键available?仍设置,以及为什么有availablenull的关键?

ruby-on-rails ruby hash
1个回答
1
投票

正如@mbuechmann说,Whois::Parser::PROPERTIES是符号的阵列。这意味着你的msg哈希具有象征性的钥匙,你不能访问它们的字符串。

msg = {}

# it is more common way for iteration in ruby
Whois::Parser::PROPERTIES.each do |prop| 
  msg[prop] = parser.send(prop)
end

msg[:available] = msg.delete(:available?)

# don't convert msg to json to check real keys format
puts msg
© www.soinside.com 2019 - 2024. All rights reserved.