Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,440 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"