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,590 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

# 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 -___-


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