Bastian
Bastian

Reputation: 207

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

Upvotes: 1

Views: 102

Answers (2)

mahemoff
mahemoff

Reputation: 46369

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

Upvotes: 2

mrzasa
mrzasa

Reputation: 23307

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

Upvotes: 2

Related Questions