简体   繁体   中英

How to use new hash syntax?

I am trying to use the new hash syntax, but it is not working. What am I doing wrong?

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" ....

The "new" hash syntax is for indexing hashes with symbols ( :key ) not strings ( 'key' or "key" ). So in your case, use:

> hash = { duplex: duplex}
> hash[:duplex]
[#<Nokogiri::XML::Element:0x1e8ee04 name="duplex"...

You can also convert the Hash using ActiveSupport::HashWithIndifferentAccess so it supports both key types. Or Hashie::Mash to make them work as methods too.

hash = Hashie::Mash.new({ duplex: duplex}) # or Hashie::Mash.new({ "duplex" => duplex }), it doesn't matter
hash[:duplex]
hash['duplex'] # same
hash.duplex # same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM