anish anil
anish anil

Reputation: 2631

How to iterate through an array of hashes in ruby

Trying to iterate over an array using ruby and it is miserably failing,

My Array
people = [{first_name: "Gary", job_title: "car enthusiast", salary: "14000" },
{first_name: "Claire", job_title: "developer", salary: "15000"},
{first_name: "Clem", job_title: "developer", salary: "12000"}]

How to iterate over the above hash to output only the salary value???

I tried using:

people.each do |i,j,k|
  puts "#{i}"
end

The results are as below and is not what i was intending,

{:first_name=>"Gary", :job_title=>"car enthusiast", :salary=>"14000"}
{:first_name=>"Claire", :job_title=>"developer", :salary=>"15000"}
{:first_name=>"Clem", :job_title=>"developer", :salary=>"12000"}

Is there a way to iterate through this array and simply list out only the salary values and not the rest?

Upvotes: 2

Views: 6308

Answers (1)

Simple Lime
Simple Lime

Reputation: 11035

In newer versions of Ruby (not sure when it was introduced, probably around ruby 2.0-ish which is when I believe keyword arguments were introduced), you can do:

people.each do |salary:,**|
  puts salary
end

where ** takes all the keyword arguments that you don't name and swallows them (ie, the first_name and job_title keys in the hash). If that isn't something that your ruby version allows, you'll need to just store the entire hash in the variable:

people.each do |person|
  puts person[:salary]
end

Upvotes: 5

Related Questions