Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active January 14, 2021 01:34
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 havenwood/039524c2754ab5428cf11118173354dd to your computer and use it in GitHub Desktop.
Save havenwood/039524c2754ab5428cf11118173354dd to your computer and use it in GitHub Desktop.
Ruby default values for Hashes (irc question)
##
# A standard Hash with default proc, which in this case sets the value to the key.
default_value_to_key = Hash.new { |hash, key| hash[key] = key }
default_value_to_key[:nope]
#=> :nope
##
# This is the same as the above proc with a Hash literal.
another_value_to_key = {}
another_value_to_key.default_proc = ->(hash, key) { hash[key] = key }
another_value_to_key[:nope]
#=> :nope
##
# Or instead of a default proc you can have a static value.
default_static = Hash.new(42)
default_static[:nope]
#=> 42
##
# This is the same as the above default with a Hash literal.
another_static = {}
another_static.default = 42
another_static[:nope]
#=> 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment