How can I “extract” values from a multidimensional array in a smart way?

 ̄綄美尐妖づ 提交于 2019-12-30 08:02:17

问题


I am using Ruby on Rails 3.2.2 and Ruby 1.9.2.

Given the following multidimensional Array:

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

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

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

How can I make that in a smart way?


回答1:


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]}

In use:

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"]

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

arr.collect(&:first)

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




回答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"]



回答3:


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

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

Solution2 = arr.transpose[0]


来源:https://stackoverflow.com/questions/11204168/how-can-i-extract-values-from-a-multidimensional-array-in-a-smart-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!