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

noMethodError : each no String

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

contact_list.each do |contact| puts "Name: #{contact["name"]}" if contact["phone_number"].size>0 contact["phone_number"].each do |phone_number| puts "Phone: #{phone_number}" end end end

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

contact_list.each do |contact|
  puts "Name: #{contact["name"]}"
    if contact["phone_number"].size>0
      contact["phone_number"].each do |phone_number|
        puts "Phone: #{phone_number}"
      end
    end
    end

1 Answer

Umar Ghouse
Umar Ghouse
14,607 Points

So, the main issue I see is this part of your answer:

if contact["phone_number"].size>0
  contact["phone_number"].each do |phone_number|
     puts "Phone: #{phone_number}"
  end
end

I'm not sure why you did that, but you don't need to.

Firstly, this is a very simple array, consisting of 2 hashes. You can see the data, which shows the phone_number key has a value in each case. So you don't need to check if it exists - but if you did want to anyway, just typing this would be sufficient:

if contact["phone_number"]
   # Do something
end

Secondly, you are trying to iterate through the phone_number. by typing contact["phone_number"].each do |phone_number|

This doesn't work since the phone_number is a string, not an array. To out put the phone number all you need to do is:

puts "Phone: #{contact["phone_number"]}"

Therefore, the final code would look something like:

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

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