I think it's written in a reference book, but instead of a memorandum.
When you want to separate an array containing multiple elements such as the following with an associative array
array = [1, 2, "a", 3, "b", "c", 4]
ideal_hash = {
hoge: [1, 2, 3, 4],
fuga: ["a", "b", "c"]
}
ideal_hash = { hoge: [], fuga: [] }
array.each do |i|
i.is_a?(Integer) ? hash[:hoge] << i : hash[:fuga] << i
end
Since the tap method returns the generated self, I can write it neatly, and I want to use it as much as possible.
ideal_hash = { hoge: [], fuga: [] }.tap do |hash|
array.each do |i|
i.is_a?(Integer) ? hash[:hoge] << i : hash[:fuga] << i
end
end
Recommended Posts