Skip to content

Instantly share code, notes, and snippets.

@andxyz
Forked from stevenharman/defaults.rb
Created April 12, 2016 05:17
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 andxyz/54448a8a1855d2d91d46859fe4b116a3 to your computer and use it in GitHub Desktop.
Save andxyz/54448a8a1855d2d91d46859fe4b116a3 to your computer and use it in GitHub Desktop.
A subtle difference between Ruby's Hash.fetch(:key, :default) vs. (Hash[:key] || :default)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment