Billy Logan
Billy Logan

Reputation: 2520

How to iterate through array of arrays on Rails template?

I've got an array in the following form:

[["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]

Is there a way to somehow display this information on a Rails template using iterators? I need something like this:

First - a, b, c

Second - d, e,

Third - g, h, i.

Or this is impossible and I should modify the initial array form?

Thanks in advance.

Upvotes: 0

Views: 56

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33491

Without modifing the main array you could try with each_with_index inside each for the main array of arrays, then checking for the first value you can skip it and get the array of letters:

array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]

array.each do |main|
  main.each_with_index do |value, index|
    next if index.zero?
    p value 
  end
end
# => ["a", "b", "c"]
#    ["d", "e"]
#    ["g", "h", "i"]

Or if you want to access it as a hash it'd be easier:

array = [["First", ["a", "b", "c"]], ["Second", ["d", "e"]], ["Third", ["g", "h", "i"]]]
array.to_h.each do |_, value|
  p value
end
# => ["a", "b", "c"]
#    ["d", "e"]
#    ["g", "h", "i"]

Upvotes: 1

Related Questions