I have an array of arrays:
我有一个数组:
arr = [["Foo1", "Bar1", "1", "W"],
["Foo2", "Bar2", "2", "X"],
["Foo3", "Bar3", "3", "Y"],
["Foo4", "Bar4", "4", "Z"]]
And I want an array containing only the third column of each of the arrays:
我想要一个数组只包含每个数组的第三列:
res = ["1", "2", "3", "4"]
How would I do that?
我该怎么做呢?
I want to type something like:
我想输入如下内容:
arr[][2]
But thinking more Ruby-like, I tried:
但我想的更像红宝石,我试着:
arr.select{ |r| r[2] }
but this returns the whole row.
但它返回整行。
3 个解决方案
#1
38
You want arr.map {|row| row[2]}
加勒比海盗。地图{ | |行[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"]
#2
14
Another method:
另一种方法:
arr.transpose[2]
#3
1
Use map or collect arr.map { |a| a[2]}
使用地图或收集arr。地图{ | |一个[2]}
#1
38
You want arr.map {|row| row[2]}
加勒比海盗。地图{ | |行[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"]
#2
14
Another method:
另一种方法:
arr.transpose[2]
#3
1
Use map or collect arr.map { |a| a[2]}
使用地图或收集arr。地图{ | |一个[2]}