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

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