Skip to content

Instantly share code, notes, and snippets.

@joonty
Last active December 22, 2015 08:58
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 joonty/6448570 to your computer and use it in GitHub Desktop.
Save joonty/6448570 to your computer and use it in GitHub Desktop.
Strange behaviour of array concatenation and each_with_object
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