oprogfrogo
oprogfrogo

Reputation: 2074

Get last value from array of arrays

arr = [[a,1], [b,3], [c,2]]

How can I convert the above array into this below:

[1,3,2]

Upvotes: 4

Views: 384

Answers (4)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Another, more explicit way to perform this operation is with Array#collect:

array = [['a', 1], ['b', 3], ['c', 2]]
array.collect { |subarray| subarray.last }

It just depends on what semantics you need to represent what you're doing.

Upvotes: 3

Andrew Marshall
Andrew Marshall

Reputation: 96914

Use map & last:

arr.map(&:last)  #=> [1,3,2]

this is equivalent to the longer

arr.map { |o| o.last }

Upvotes: 6

shouya
shouya

Reputation: 3083

Just simply arr.map(&:last).

Upvotes: 3

Ray Toal
Ray Toal

Reputation: 88378

If each element is a 2-element array, then just like this

arr.map{|x,y| y}

Upvotes: 1

Related Questions