Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Last active December 15, 2015 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmarreck/5205946 to your computer and use it in GitHub Desktop.
Save pmarreck/5205946 to your computer and use it in GitHub Desktop.
Why Ruby hash key format ambiguity is dangerous.
>> require 'active_support/all'
=> true
>> hwia = HashWithIndifferentAccess[:a, 1, :b, 2]
=> {:a=>1, :b=>2} # uh... ok so maybe they didn't define self.[]= . but all is not lost... yet. let's continue.
>> hwia
=> {:a=>1, :b=>2} # well, they're supposed to always be strings internally, but let's try anyway
>> hwia['a']
=> nil # ORLY.
>> hwia.merge!({:a => 11, 'a' => 12})
=> {:a=>1, :b=>2, "c"=>3, "a"=>12} # For fuck's sake.
>> hwia['a']
=> 12 # Well, finally something makes sense. Sorta. Until...
>> hwia[:a]
=> 1 # Noooooooooo
# OK start over
>> hwia = HashWithIndifferentAccess.new
=> {}
>> hwia[:a]=1
=> 1
>> hwia.merge({a: 2, 'a' => 3})
=> {"a"=>3}
>> hwia.merge({a: 3, 'a' => 2})
=> {"a"=>2}
>> hwia.merge({'a' => 4, :a => 5})
=> {"a"=>5} # OK, so it always takes the last indifferently-accessed key value. I actually think it should raise in this case.
>> {'a' => 4, :a => 5}.merge(hwia)
=> {"a"=>1, :a=>5} # Probably not entirely what was expected. I think it should actually overwrite both values, for example. Or raise.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment