Last active
December 3, 2021 06:18
-
-
Save nashirox/c582c2e250e20610e14dd11202b62686 to your computer and use it in GitHub Desktop.
Samples to building an hash key\value pairs in a conditional way.
This file contains 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
# case1 | |
Hash.new.tap do |hash| | |
hash[:key1] = value1 if condition_1 | |
hash[:key2] = value2 if condition_2 | |
end | |
# case2 | |
hash = {} | |
hash[:key1] = value1 | |
hash[:key2] = value2 if condition_2 | |
hash[:key3] = value3 | |
# case3 | |
hash = { | |
key1: value1, | |
key2: (value2 if condition_2), | |
key3: value3, | |
}.compact | |
# case4 | |
hash = { | |
key1: value1, | |
key3: value3, | |
} | |
hash[:key2] = value2 if condition_2 | |
# case5 | |
hash = { | |
key1: value1, | |
key3: value3, | |
}.merge(condition_2 ? { key2: value2 } : {}) | |
# case6 | |
hash = { | |
key1: value1, | |
key3: value3, | |
}.tap { |h| h[:key2] = value2 if condition_2 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment