user3625605
user3625605

Reputation: 323

What is the best way to access an element from 2d array saved as a hash value?

I have a hash, its values are 2 dimensional arrays, e.g.

hash = {
"first" => [[1,2,3],[4,5,6]],
"second" => [[7,88,9],[6,2,6]]     
}

I want to access the elements to print them in xls file.

I did it in this way:

hash.each do |key, value|
  value.each do |arr1|
    arr1.each do |arr2|
      arr2.each do |arr3|
        sheet1.row(row).push arr3
      end
    end
  end
end

Is there a better way to access each single element without using each-statement 4 times?

The desired result is to get each value from key-value pair as an array, e.g.

=> [1,2,3,4,5,6] #first loop
=> [7,88,9,6,2,6] #second loop
 #and so on

Upvotes: 1

Views: 93

Answers (2)

jvillian
jvillian

Reputation: 20253

Isn't it as simple as something like:

hash.each do |k,v|
  sheet1.row(row).concat v.flatten
end

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110755

hash = { "first" =>[[1, 2,3],[4,5,6]],
         "second"=>[[7,88,9],[6,2,6]] }

hash.values.map(&:flatten)
  #=> [[1, 2, 3, 4, 5, 6], [7, 88, 9, 6, 2, 6]]

Upvotes: 3

Related Questions