Skip to content

Instantly share code, notes, and snippets.

@havenwood

havenwood/hash_defaults.rb

Last active Jan 14, 2021
Embed
What would you like to do?
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