dan-mi-sun
dan-mi-sun

Reputation: 541

Convert row of string dates to array of Date objects

I have a 2d array that contains some nil values.

require 'date'
array = [["2014-01-12", "2014-01-12", "2014-01-12"],
          ["2012-08-26", "2012-10-18", nil],
          ["2013-04-09", "2013-05-22", "2013-07-01"]]

The desired result is an array of date objects. The resulting array should look like this (Date objects for display purposes):

changed_array = [#<Date: 2014-01-12 ((2456874j,0s,0n),+0s,2299161j)>, nil, #<Date: 2012-07-31 ((2456874j,0s,0n),+0s,2299161j)>]

I considered something like:

changed_array = array.map { |due| (Date.strptime(due[2], "%Y-%m-%d")) unless (due[2] == nil) }

Any input is appreciated.

EDIT:

As a newbie to coding I would appreciate any input on alternative approaches to this solution!

Upvotes: 1

Views: 1036

Answers (2)

Santhosh
Santhosh

Reputation: 29174

Similar to Uri's solution, but with only one map

array.map {|*_, d| Date.parse(d) if d}
# => [#<Date: 2014-01-12 ((2456670j,0s,0n),+0s,2299161j)>, nil, #<Date: 2013-07-01 ((2456475j,0s,0n),+0s,2299161j)>]

Upvotes: 2

Uri Agassi
Uri Agassi

Reputation: 37419

If you want the last element to be parsed into date you can do the following:

changed_date = array.map(&:last).map { |d| Date.parse(d) if d }
# => [#<Date: 2014-01-12 ((2456670j,0s,0n),+0s,2299161j)>, nil, #<Date: 2013-07-01 ((2456475j,0s,0n),+0s,2299161j)>] 

The first map takes only the last element of each array, and the second parses the date, unless it is nil.

Upvotes: 1

Related Questions