0

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.

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.