I have a array like this
arr = [{:id=>1}, {:id=>2}, {:id=>3}, {:id=>4}, {:id=>5}, {:id=>6}, {:id=>7}, {:id=>8}]
The result should be
result = [1, 2, 3, 4, 5, 6, 7, 8]
I used arr.map { |i| i.values }
arr.map { |i| i.values }
.However, the result is [[1], [2], [3], [4], [5], [6], [7], [8]]
. Please help.
You should flatten the result, to get your desired output :
arr.flat_map { |i| i.values }
Read flat_map
.
I don't know actual intention of yours, still if you want to collect all ids , you can write :
arr.collect { |h| h[:id] }
use flatten
For return an one-dimensional a new array that is a one-dimensional flattening of this array (recursively)
arr.map {|i| i.values}.flatten
Or simply map all ids
arr.collect {|i| i[:id]}
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.