Last active
January 14, 2021 01:34
-
-
Save havenwood/039524c2754ab5428cf11118173354dd to your computer and use it in GitHub Desktop.
Ruby default values for Hashes (irc question)
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
## | |
# 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