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.
You want 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"]
Another method:
arr.transpose[2]
Use map or collect arr.map { |a| a[2]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With