johnmc321
johnmc321

Reputation: 89

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.

Upvotes: 0

Views: 9838

Answers (2)

oldergod
oldergod

Reputation: 15010

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

Upvotes: 1

Rafal
Rafal

Reputation: 2576

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

Upvotes: 6

Related Questions