在 Ruby 中遍历数组数组的更好语法

Nicer syntax for looping through array of arrays in Ruby

我有A,一个长度为3的数组。例如A = [[a1, b1, c3], [a2, b2, c2], [a3, b3, c3], [a4, b4 , c4]]。现在我像这样循环它:

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

由于我在循环中使用了很多不同的属性,代码变得非常混乱且难以阅读。另外,本地名称 elem[0] 的描述性不强。有没有办法使用这样的东西?

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

我是 ruby 的新手,我真的不知道去哪里找这样的东西。

它被称为de-structuring(或在Ruby docs中分解):

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

如果元素数量未知,您也可以使用 splat (*),它将收集剩余的元素:

[[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