Christian Doucette
Christian Doucette

Reputation: 1314

Nicer syntax for looping through array of arrays in Ruby

I have A, an array of arrays of length 3. For example A = [[a1, b1, c3], [a2, b2, c2], [a3, b3, c3], [a4, b4, c4]]. Right now I am looping over it like this:

A.each do |elem|
  puts(elem[0].foo)
  puts(elem[1].bar)
  puts(elem[2].baz)
end

Since I am using a lot of different properties in the loop, the code gets pretty messy and unreadable. Plus, the local name elem[0] isn't very descriptive. Is there a way to use something like this?

A.each do |[a,b,c]|
  puts(a.foo)
  puts(b.bar)
  puts(c.baz)
end

I'm pretty new to ruby I don't really know where to look for something like this.

Upvotes: 1

Views: 91

Answers (1)

max
max

Reputation: 102036

Its known as de-structuring (or decomposition in the Ruby docs):

A.each do |(a,b,c)|
  puts(a.foo)
  puts(b.bar)
  puts(c.baz)
end

You can also use a splat (*) if the number of elements is unknown which will gather the remaining elements:

[[1, 2, 3, 4], [5, 6, 7, 8]].each do |(first, *rest)|
  puts "first: #{first}"
  puts "rest: #{rest}"
end


[[1, 2, 3, 4], [5, 6, 7, 8]].each do |(first, *middle, last)|
  puts "first: #{first}"
  puts "middle: #{middle}"
  puts "last: #{last}"
end

Upvotes: 4

Related Questions