[Ruby] Define the hierarchy at the same time as Hash initialization with tap method

I think it's written in a reference book, but instead of a memorandum.

For example

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"]
}

The code I've written so far


ideal_hash = { hoge: [], fuga: [] }

array.each do |i|
  i.is_a?(Integer) ? hash[:hoge] << i : hash[:fuga] << i
end

I recently learned that I can write this too

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

[Ruby] Define the hierarchy at the same time as Hash initialization with tap method
Setting to start multiple units at the same time with Vagrant
Draw a bar graph and a line graph at the same time with MPAndroidChart
[Ruby] Exclude duplicate elements with the uniq method.
Finding pi with the Monte Carlo method? (Ruby)
How to delete the tweet associated with the user when you delete it at the same time
Form and process file and String data at the same time with Spring Boot + Java
[At Coder] Solve the ABC183 D problem with Ruby
[At Coder] Solve the ABC182 D problem with Ruby
Java desktop with the same front end as the WEB.
[Java] Method call error when inheritance and interface implementation are performed at the same time
Hello World with Ruby extension library for the time being
In Ruby you can define a method with any name
Ruby / rexml: Turn each with an element with the same name