我正在尝试使用新的散列语法,但它不起作用。我做错了什么?
2.6.3 :151 > hash = { duplex: duplex}
=> {:duplex=>[#<Nokogiri::XML::Element:0x1e8ee04 name="duplex"....
2.6.3 :152 > hash["duplex"]
=> nil
2.6.3 :153 > hash = { "duplex" => duplex}
=> {"duplex"=>[#<Nokogiri::XML::Element:0x1e8ee04 name="duplex" ....
2.6.3 :154 > hash["duplex"]
=> [#<Nokogiri::XML::Element:0x1e8ee04 name="duplex" ....发布于 2019-07-17 16:05:34
“新的”散列语法用于索引带有符号(:key)而不是字符串('key'或"key")的散列。因此,在您的示例中,请使用:
> hash = { duplex: duplex}
> hash[:duplex]
[#<Nokogiri::XML::Element:0x1e8ee04 name="duplex"...发布于 2019-07-17 16:43:20
您还可以使用ActiveSupport::HashWithIndifferentAccess转换Hash,以便它支持这两种键类型。或者Hashie::Mash使它们也可以作为方法工作。
hash = Hashie::Mash.new({ duplex: duplex}) # or Hashie::Mash.new({ "duplex" => duplex }), it doesn't matter
hash[:duplex]
hash['duplex'] # same
hash.duplex # samehttps://stackoverflow.com/questions/57071213
复制相似问题