从Ruby中的数组数组中的一列中选择所有元素?

rwb*_*rwb 27 ruby

我有一个数组数组:

arr = [["Foo1", "Bar1", "1", "W"], 
["Foo2", "Bar2", "2", "X"], 
["Foo3", "Bar3", "3", "Y"], 
["Foo4", "Bar4", "4", "Z"]]
Run Code Online (Sandbox Code Playgroud)

我想要一个只包含每个数组的第三列的数组:

res = ["1", "2", "3", "4"]
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

我想输入类似的东西:

arr[][2]
Run Code Online (Sandbox Code Playgroud)

但是考虑更像Ruby,我试过:

arr.select{ |r| r[2] }
Run Code Online (Sandbox Code Playgroud)

但这会返回整行.

Cho*_*ett 48

你要 arr.map {|row| row[2]}

arr = [["Foo1", "Bar1", "1", "W"], 
["Foo2", "Bar2", "2", "X"], 
["Foo3", "Bar3", "3", "Y"], 
["Foo4", "Bar4", "4", "Z"]]

arr.map {|row| row[2]}
# => ["1", "2", "3", "4"]
Run Code Online (Sandbox Code Playgroud)

  • 或者使用Rails/ActiveSupport的`arr.map(&:third)`. (9认同)
  • 还有#first和#last在纯红宝石中可用 (2认同)

ste*_*lag 15

另一种方法:

arr.transpose[2]
Run Code Online (Sandbox Code Playgroud)