Search code examples
rubyarrayshashenumerable

Populate new_hash where the unique values from old_hash are the keys, and the keys from old_hash are values, grouped into arrays.


I am new to programing and am starting with Ruby. Using .each ONLY, my challenge is to turn this:

animals = {
  'leopard'   => 1,
  'gorilla'   => 3,
  'hippo'     => 4,
  'zebra'     => 1,
  'lion'      => 2,
  'eagle'     => 3,
  'ostrich'   => 2,
  'alligator' => 6
}

Into this hash where the animals are grouped by count:

animals_by_count = {
   1 => ['leopard', 'zebra'],
   2 => ['lion', 'ostrich'],
   3 => ['gorilla', 'eagle'],
   4 => ['hippo'],
   6 => ['alligator']
}

This is my code, it is not working properly. Again, I must use .each ONLY, I my NOT use .map .inject .select or any another method.

animals_by_count = {}
animals.each do |animal, count|
  animals_array = []
  if !animals_by_count.has_key?(count)
    animals_by_count[count] = animals_array << animal
  elsif animals_by_count.has_key?(count)
    animals_by_count[count] = animals_array << animal
  end

 end

Solution

  • You can do as below :-

    animals = {
      'leopard'   => 1,
      'gorilla'   => 3,
      'hippo'     => 4,
      'zebra'     => 1,
      'lion'      => 2,
      'eagle'     => 3,
      'ostrich'   => 2,
      'alligator' => 6
    }
    
    animals_by_count = {}
    animals.each do |animal, count|
      if animals_by_count.has_key?(count)
        animals_by_count[count].push(animal)
      else
        animals_by_count[count] = [animal]
      end
    end
    
    animals_by_count
    # => {1=>["leopard", "zebra"],
    #     3=>["gorilla", "eagle"],
    #     4=>["hippo"],
    #     2=>["lion", "ostrich"],
    #     6=>["alligator"]}
    

    Why not worked your one ?

    animals.each do |animal, count|
      animals_array = []
    # see here at every iteration, you are creating a new empty array and using it.
    # animals_by_count key thus holding the last array, loosing the previous one.