简体   繁体   中英

Building an array of hashes with two key/value pairs from Rails array

I have an array that looks like this:

[172336, 60, 172339, 64, 172342, 62, 172345, 61, 172348, 62, .....]

I'm trying to convert it to an array of hashes where each hash has two key/value pairs, the key is either 'time' or 'elevation', and the values for the 'time' hashes are indexed at [0], [2], [4], etc., while 'elevation' is at [1], [3], etc. So, it would look something like:

[{time => 172336, elevation => 60}, {time => 172339, elevation => 64}, {time => 172342, elevation => 62},.....]

Getting each item is easy enough with something like:

my_array.each do |x|
 new_array << {:time => x}
end

but that's obviously going to assign each value to a 'time' key. I can't figure out how to get at every second item.

you can try using each_slice(2) which will batch the returned results by 2

 my_array.each_slice(2) do |value| 
  array << {:time => value[0], :elevation => value[1]}
end

Hope this helps

You could do

keys = [:time, :elevation]
values = [172336, 60, 172339, 64, 172342, 62, 172345, 61, 172348, 62]

array = values.each_slice(2).map { |value| Hash[keys.zip(value)] }
# [{:time=>172336, :elevation=>60},
#  {:time=>172339, :elevation=>64},
#  {:time=>172342, :elevation=>62},
#  {:time=>172345, :elevation=>61},
#  {:time=>172348, :elevation=>62}]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM