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

How can I convert the above array into this below:

[1,3,2]

4 Answers 4

6

Use map & last:

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

this is equivalent to the longer

arr.map { |o| o.last }
Sign up to request clarification or add additional context in comments.

Comments

3

Just simply arr.map(&:last).

Comments

3

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.

Comments

1

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

arr.map{|x,y| y}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.