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