如何以智能方式从多维数组中“提取”值?

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

给定以下多维Array

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

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

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

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

您可以使用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 |  IND [0]}
 => [“value1”,“value2”,“value3”]

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

 arr.collect(&:first) 

对于&:first语法,请阅读“ Ruby / Ruby on Rails&符号冒号 ”。

 >> 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"] 
 arr = [["value1", "value1_other"], ["value2", "value2_other"], ["value3", "value3_other"]] Solution1 = arr.map {|elem| elem.first} Solution2 = arr.transpose[0]