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

How do you return/print each value of an array within a ash within an array?

From this sample code:

contact = [ {name: "Sebastien", numbers [01245131, 4574568]}]

My print_contact methods aims to print out each key and value of the hash within the contact array:

def print_contact contact.each do |index| index.each do |key, value| puts "#{key} : #{value}" end end end

The result of this method prints:

Your contact list:
name : sebastien
numbers : [10292020, 202020202]

So my question is: How do I print the value inside the array and not the array itself.

Thanks!

1 Answer

Try this, without two .each methods:

contact = [ {name: "Sebastien", numbers: [01245131, 4574568]} ]

contact.each do |index| 
    puts "name : #{index[:name]}"
    puts "numbers: #{index[:numbers][0]}, #{index[:numbers][1]}"
end

This assumes that every object in the array will be formatted the same way - it will have the key :name and the key :numbers which will be an array of at least two elements.

Thanks Maciej!

What if you don't know the length of the numbers: array?

Then you can use another .each for just the numbers array. Something like this:

contact = [ {name: "Sebastien", numbers: [01245131, 4574568]} ]

def converter(array)
    number_string = ""
    array.each { |number| number_string = number_string + "#{number}" + ", " }
    return number_string
end

contact.each do |index| 
    puts "name : #{index[:name]}"
    puts "numbers: " + converter(index[:numbers])
end

Please note that 01245131 is not converted into the same number when in a string. It becomes 346713, because Ruby thinks it's an octal number (leading 0).