user3000487
user3000487

Reputation: 13

Ruby: changing type of only part of an array

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?

Upvotes: 1

Views: 65

Answers (3)

hirolau
hirolau

Reputation: 13921

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

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88418

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

Upvotes: 1

sawa
sawa

Reputation: 168199

["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

Upvotes: 2

Related Questions