Home > other >  How to iterate over an array of hashes in Ruby and return all of the values of a specific key in a s
How to iterate over an array of hashes in Ruby and return all of the values of a specific key in a s

Time:12-15

I'm currently trying to iterate over an array of hashes, and return all of the values of the "name" key in a string. Here's the array:

foods = 

  [
    { name: 'Dan Dan Noodles', cuisine: 'Sichuan', heat_level: 8 },
    { name: 'Nashville Hot Chicken', cuisine: 'American', heat_level: 7 },
    { name: 'Panang Curry', cuisine: 'Thai', heat_level: 4 },
  ]

Here's what I'm currently doing, and I'm not totally sure why it's not working!

  foods.each do |food|
    food.each do |k, v|
      if food == :name
        "#{v}"
      end
    end
  end

Thanks in advance.

CodePudding user response:

You can use Enumerable#map for this:

p foods.map { |f| f[:name] }

The code you tried to use did not produce any output or create any objects, and it was not necessary to use a second loop to access a single element of a hash.

  • Related