1

I have a whole bunch of arrays, each with integers as strings in slots 1 and 3 through 9, but in each array slot 2 has a time in it (as a string), in minutes:seconds. A sample array would look like this:

["1", "11:49", "345", "26", "123456", "23", "1", "0", "65"]

What I want to do is convert everything except the time into integers, and convert the time into an integer number of seconds. How would I go about this?

3 Answers 3

2
["1", "11:49", "345", "26", "123456", "23", "1", "0", "65"]
.map.with_index do |e, i|
  if i == 1
    m, s = e.scan(/\d+/)
    m.to_i.*(60) + s.to_i
  else
    e.to_i
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. Only thing I don't quite understand (forgive me, I'm new to ruby) is how I make an output array from this...
Wondering what was going on until I realized I made a typo and wrote it in wrong. Sorry about that, everything working now.
1

A slower but possibly more readable version sets the second element of a clone of your original array, then maps the to_i method

>> original = ["1", "11:49", "345", "26", "123456", "23", "1", "0", "65"]

>> a = original.clone
=> ["1", "11:49", "345", "26", "123456", "23", "1", "0", "65"]
>>  m, s = a[1].split(":")
=> ["11", "49"]
>>  a[1] = m.to_i * 60 + s.to_i
=> 709
>> a.map(&:to_i)
=> [1, 709, 345, 26, 123456, 23, 1, 0, 65]

In a function:

def f(array)
  a = array.clone
  m, s = a[1].split(":")
  a[1] = m.to_i * 60 + s.to_i
  a.map(&:to_i)
end

1 Comment

Ray, I like your approach of avoiding unnecessary ifs within the loop. You could eliminate the need to clone with: def f(array); m, s = a[1].split(":").map(&:to_i); a = array.map(&:to_i); a[1] = m * 60 + s; a; end. Note "11:30".to_i => 11; i.e., it does not raise an exception.
0

I would do it like this:

time_to_seconds = -> x {m,s=x.split(':').map(&:to_i);m*60+s}

my_array.map do |num|
  num[':'] ? time_to_seconds[num] : num.to_i
end

1 Comment

But why do the extra work, considering that we know the location of the sole exceptional item (and we probably should be checking that)?

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.