Last active
July 7, 2021 14:36
-
-
Save stevenharman/5664318 to your computer and use it in GitHub Desktop.
A subtle difference between Ruby's Hash.fetch(:key, :default) vs. (Hash[:key] || :default)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h = { | |
'a' => :a_value, | |
'b' => nil, | |
'c' => false | |
} | |
h.fetch('a', :default_value) #=> :a_value | |
h.fetch('b', :default_value) #=> nil | |
h.fetch('c', :default_value) #=> false | |
h.fetch('d', :default_value) #=> :default_value | |
(h['a'] || :default_value) #=> :a_value | |
(h['b'] || :default_value) #=> :default_value | |
(h['c'] || :default_value) #=> :default_value | |
(h['d'] || :default_value) #=> :default_value |
You can get exactly same result if you do Hash.fetch(:key, ::default_value) || :default_value
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fetch
does return a default value, presuming you provide one. You can also provide a block, the return value of which, will be used as the "default value" in the case the key is missing from the hash.