我如何“提取"到智能方式从多维数组中获取值? [英] How can I "extract" values from a multidimensional array in a smart way?

查看:75
本文介绍了我如何“提取"到智能方式从多维数组中获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ruby on Rails 3.2.2和Ruby 1.9.2.

I am using Ruby on Rails 3.2.2 and Ruby 1.9.2.

给出以下多维Array:

[["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]

我想得到( note :我只想提取"所有嵌套" Array s的第一个值):

I would like to get (note: I would like to "extract" only the first value of all "nested" Arrays):

["value1", "value2", "value3"]

我如何以一种聪明的方式做到这一点?

推荐答案

您可以使用

You can use Array#collect to execute a block for each element of the outer array. To get the first element, pass a block that indexes the array.

arr.collect {|ind| ind[0]}

使用中:


arr = [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
=> [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
arr.collect {|ind| ind[0]}
=> ["value1", "value2", "value3"]

代替{|ind| ind[0]},您可以使用

Instead of {|ind| ind[0]}, you can use Array#first to get the first element of each inner array:

arr.collect(&:first)

对于&:first语法,请阅读" Ruby/Ruby on Rails&符冒号快捷方式".

For the &:first syntax, read "Ruby/Ruby on Rails ampersand colon shortcut".

这篇关于我如何“提取"到智能方式从多维数组中获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆