Last active
December 22, 2015 08:58
-
-
Save joonty/6448570 to your computer and use it in GitHub Desktop.
Strange behaviour of array concatenation and each_with_object
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
def flatten_keys(hsh, keys) | |
keys.each_with_object([]) { |k, result| | |
result += hsh[k] | |
} | |
end | |
def flatten_keys_each(hsh, keys) | |
result = [] | |
keys.each { |k| | |
result += hsh[k] | |
} | |
result | |
end | |
def flatten_keys_concat(hsh, keys) | |
keys.each_with_object([]) { |k, result| | |
result.concat hsh[k] | |
} | |
end | |
hsh = { | |
:a => [1, 2, 3], | |
:b => [4, 5, 6], | |
:c => [7, 8, 9] | |
} | |
p flatten_keys(hsh, [:a, :c]) #=> [] | |
p flatten_keys_each(hsh, [:a, :c]) #=> [1, 2, 3, 7, 8, 9] | |
p flatten_keys_concat(hsh, [:a, :c]) #=> [1, 2, 3, 7, 8, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment