简体   繁体   中英

Get last value from array of arrays

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

如何将上面的数组转换为以下数组:

[1,3,2]

Use map & last :

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

this is equivalent to the longer

arr.map { |o| o.last }

只需简单地arr.map(&:last)

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.

如果每个元素都是一个2元素数组,那么就像这样

arr.map{|x,y| y}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM