Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all elements from one column in an array of arrays in Ruby?

Tags:

ruby

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.

like image 222
rwb Avatar asked Jul 27 '12 13:07

rwb


3 Answers

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"]
like image 66
Chowlett Avatar answered Nov 13 '22 02:11

Chowlett


Another method:

arr.transpose[2]
like image 22
steenslag Avatar answered Nov 13 '22 02:11

steenslag


Use map or collect arr.map { |a| a[2]}

like image 1
Pritesh Jain Avatar answered Nov 13 '22 01:11

Pritesh Jain