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

My code works but still got a message saying otherwise

for each contact i print the value of its name and phone number. isnt that what im suppose to do?

contact_list.rb
contact_list = [
  {"name" => "Jason", "phone_number" => "123"},
  {"name" => "Nick", "phone_number" => "456"}
]
contact_list.each do |contact|
  contact.each_value do |value|
    puts value
  end

end 

1 Answer

John Coolidge
John Coolidge
12,614 Points

Hello Stella,

The exercise wants you to print out each name and phone number using the puts method by using the .each method.

When you structure your .each method, you take the name of the hash or array (contact_list), add .each to it, followed by do, followed by a variable, in this case, contact. You have as much in your example:

contact_list.each do |contact|
  contact.each_value do |value|
    puts value
  end

The first problem is, you've got an unnecessary .each method in your example above. You can remove it, leaving this:

contact_list.each do |contact|    
  puts value
end

Now you're getting closer. You will need to print out both the contact name and phone number to the screen. So, the next question is, how do you access the values in a hash? You need to use the following:

contact["name"] #to access the name

contact["phone_number"] #to access the phone number

Each hash in the array is saved under the local variable "contact" and in order to access the key "name" you need to put it in brackets after the hash, which in this case is stored in the variable "contact".

So, in order to put all of this together you need to set up your .each method as I described above.

When you decide what you want to puts, namely the contact information, all you need to do is supply the contact["name"] and the contact["phone_number"] after "puts", using a comma to separate them.

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

I hope this assists in explaining how to access hash key/values in an array using the .each method.

John