13

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

给定以下多维Array

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

我想得到(注意:我只想“提取”所有“嵌套”Array的第一个值):

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

我怎样才能以聪明的方式做到这一点?

4

3 回答 3

27

您可以使用Array#collect为外部数组的每个元素执行一个块。要获取第一个元素,请传递一个索引数组的块。

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| 工业[0]}
=> ["value1", "value2", "value3"]

而不是{|ind| ind[0]},您可以使用Array#first来获取每个内部数组的第一个元素:

arr.collect(&:first)

有关&:first语法,请阅读“ Ruby/Ruby on Rails & 和冒号快捷方式”。

于 2012-06-26T09:19:11.397 回答
2
>> array = [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
=> [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]
>> array.map { |v| v[0] }
=> ["value1", "value2", "value3"]
于 2012-06-26T09:20:21.683 回答
1
arr = [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]]

Solution1 = arr.map {|elem| elem.first}

Solution2 = arr.transpose[0]
于 2017-07-25T20:24:19.620 回答