Fran
Fran

Reputation: 11

How to split a String in a multidimensional Array in ruby?

I have an multidimensional Array in Ruby, like this:

[["2013-08-22 13:23:12 +0212", 100, 1], ["2013-09-22 14:25:12 +0123" , 123, 1]]

I would like to split the string in the first array position and the time to hours, minutes and seconds (and convert these to integers), so it will become:

[["2013-08-22", 13, 23, 12, "+0212", 100, 1], [.....]]

Does anyone know how to solve this problem?

Upvotes: 0

Views: 1114

Answers (4)

ardavis
ardavis

Reputation: 9895

If you would like more readability, I suggest this:

require 'date'
array = [["2013-08-22 13:23:12 +0212", 100, 1], ["2013-09-22 14:25:12 +0123" , 123, 1]]
array.map do |date_time, a, b|
  date_time = DateTime.parse(date_time)

  [
    date_time.strftime('%F'), date_time.hour, date_time.min,
    date_time.sec, date_time.strftime('%z'), a, b
  ]
end

It makes it very clear what each element of the resulting array is. You should replace a and b with meaningful names if you have them.

Upvotes: 2

cavin kwon
cavin kwon

Reputation: 501

Non-destructive way. ref @mudasobwa answer

arr = [["2013-08-22 13:23:12 +0212", 100, 1], ["2013-09-22 14:25:12 +0123" , 123, 1]]
arr.map {|e| e[0].split(/[ :]/) + e[1..-1] } 
#=> [["2013-08-22", "13", "23", "12", "+0212", 100, 1], ["2013-09-22", "14", "25", "12", "+0123", 123, 1]]

Upvotes: 0

Gerry
Gerry

Reputation: 10497

Here's another option (converting hours, minutes and seconds to integers):

arr = [["2013-08-22 13:23:12 +0212", 100, 1], ["2013-09-22 14:25:12 +0123" , 123, 1]]

arr.map do |item|
  date, time, zone = item[0].split.map { |e| e.split(":") }
  [date, time.map(&:to_i), zone, item[1..-1]].flatten
end
#=> [["2013-08-22", 13, 23, 12, "+0212", 100, 1], ["2013-09-22", 14, 25, 12, "+0123", 123, 1]]

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

[["2013-08-22 13:23:12 +0212", 100, 1],
 ["2013-09-22 14:25:12 +0123" , 123, 1]].

   map do |arr|
     arr.shift.split(/[: ]/) + arr # first position only
     # ⇓ this will convert hours, minutes and seconds  to integers
     # arr.shift.split(/[: ]/).map { |e| e[/\A\d+\z/] ? e.to_i : e } + arr
     # ⇓ this would work for all strings
     # arr.flat_map { |e| e.is_a?(String) ? e.split(/[: ]/) : e }
   end
#⇒ [
#  [0] [
#    [0] "2013-08-22",
#    [1] "13",
#    [2] "23",
#    [3] "12",
#    [4] "+0212",
#    [5] 100,
#    [6] 1
#  ],
#  [1] [
#    [0] "2013-09-22",
#    [1] "14",
#    [2] "25",
#    [3] "12",
#    [4] "+0123",
#    [5] 123,
#    [6] 1
#  ]
# ]

Upvotes: 1

Related Questions