0

I have this array of time values:

["00:04:48.563044", "00:05:29.835918", "00:09:38.622569"]

But I need to pass each array item through a parser (in this case, chronic_duration), and then spit it back out in to an array.

So each array item would need to get passed through:

ChronicDuration.parse('00:04:48.563044')

And then put back in an array:

[288.563044, 329.835918, 578.622569]

1 Answer 1

5

Two obvious options; new array, or in-place.

pry(main)> arr = ["00:04:48.563044", "00:05:29.835918", "00:09:38.622569"];
pry(main)> arr.collect! { |s| ChronicDuration.parse s }
=> [288.563044, 329.835918, 578.622569]

To create a new array, leave off the exclamation point ("!") on the collect call:

pry(main)> new_arr = arr.collect { |s| ChronicDuration.parse s }

You might want to map from one to the other:

pry(main)> h = Hash[arr.collect { |s| [s, ChronicDuration.parse(s)] }]
=> {"00:04:48.563044"=>288.563044,
 "00:05:29.835918"=>329.835918,
 "00:09:38.622569"=>578.622569}

Or switch the keys/values to allow easy sorting; either switching the collect array, or inverting:

pry(main)> h.invert.keys.sort.each_with_index {|k, i| puts "#{i+1}: #{h[k]}"}
1: 00:04:48.563044
2: 00:05:29.835918
3: 00:09:38.622569
Sign up to request clarification or add additional context in comments.

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.