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 Ruby Iteration Hash Iteration

how would I iterate and return all of the array items within the hash?

on Ruby Loops - Hash Iteration i would like to know how to access each value within an array, for example:

hash = { "names" => ["value1", "value2", value3"] , "years" => [2013, 2014, 2015] }

how would i iterate through each value in the array?

hash.each do |??| #what would I do? end

2 Answers

Tobias Helmrich
Tobias Helmrich
31,603 Points

Hey there Aron,

I hope I understood your question correctly. If so, you can iterate over the arrays in your hash just like you're iterating over the hash - with the each method. You have to use the each method on the arrays inside of the block of the each method on the hash.

Here is a simple example, assuming that every value inside of the hash is an array:

my_hash = { "names" => ["value1", "value2", "value3"], "years" => [2013, 2014, 2015] }

my_hash.each do |key, value|
  value.each do |array_value|
    puts array_value
  end
end

# outputs:
# value1
# value2
# value3
# 2013
# 2014
# 2015

I hope that answers your question, if not or if you have further questions feel free to ask! :)

so easy, i should have just tried it -___-

thanks!

Vlad Filiucov
Vlad Filiucov
10,665 Points

if you want to have an array of values you can do something like: my_hash.values.flatten