Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Loops Build a Simple Contact List Hash and Array Iteration

Hash and Array Iteration

I don't understand what I'm doing wrong? Can someone help me? The question is: Using the each method, iterate over the contact_list array. Assign each array item to the local variable contact in the block and print out the value of the name and phone_number keys.

This is my code:

contact_list = [
  {"name" => "Jason", "phone_number" => "123"},
  {"name" => "Nick", "phone_number" => "456"}
  ]

contact_list.each do |contact|
  puts "Name: #{contact["name"]}"
  puts "Phone Number: #{contact["phone_number"]}"

3 Answers

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

You're close, but they only want the values,without any additional stuff, like this:

contact_list = [
  {"name" => "Jason", "phone_number" => "123"},
  {"name" => "Nick", "phone_number" => "456"}
]

contact_list.each do |contact|
  puts contact["name"]
  puts contact["phone_number"]
end

It worked! Thank you so much!

Mars Epaecap
Mars Epaecap
5,110 Points

I found this way to be least confusing

contact_list = [
  {"name" => "Jason", "phone_number" => "123"},
  {"name" => "Nick", "phone_number" => "456"}
]

contact_list.each do |items|
  items.each do |key, value|
    puts "name"
    puts "phone_number"
  end
end
Saad Khan Malik
Saad Khan Malik
25,199 Points

I tried it a different way,

contact_list.each do |x|
  x.each_pair do |key, value|
    puts key
    puts value
  end
end

According to the tutorial but it doesn't work. Any ideas why?

Mars Epaecap
Mars Epaecap
5,110 Points

@Saad Khan Malik it has to be like this:

contact_list.each do |x|
  x.each_pair do |key, value|
    puts "name"
    puts "phone_number"
  end
end

You just had to use "name" and "phone_number"