I’ve got some issue with DateTime in Ruby
I’ve got line which looks like this (it’s in .txt file)
DateTime.new(1979,1,1) DateTime.new(2012,3,29)
And my function to get this looks like this
def split_line
array = line.split(' ')
@date_of_birth = array[0]
@date_of_death = array[1]
end
But @date_of_birth
and @date_of_death
class are String. How can I get them as DateTime?
3
3 Answers
Assuming your string is in the correct format, then you’re probably looking for:
@date_of_birth = array[0].to_datetime
@date_of_death = array[1].to_datetime
See here for more info:
This:
DateTime.new(1979,1,1) DateTime.new(2012,3,29)
Is not code. What do you expect that to do?
If you want two DateTimes
as a space-separated string, do something like:
"#{DateTime.new(1979,1,1)} #{DateTime.new(2012,3,29)}"
When you have something like #{...}
inside a set of double quotation marks (they must be double, not single quotation marks), it’s called string interpolation
. Learn it. Love it. Live it.
But, for the life of me, I don’t know why you wouldn’t do:
[DateTime.new(1979,1,1), DateTime.new(2012,3,29)]
Which gives you an array
, so no split
needed. Just:
def split_line
@date_of_birth = array[0]
@date_of_death = array[1]
end
If you want DateTime values, grab the numbers and create them:
require 'date'
'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split.map { |s|
DateTime.new(*s.scan(/d+/).map(&:to_i) )
}
# => [#<DateTime: 1979-01-01T00:00:00+00:00 ((2443875j,0s,0n),+0s,2299161j)>,
# #<DateTime: 2012-03-29T00:00:00+00:00 ((2456016j,0s,0n),+0s,2299161j)>]
The values aren’t DateTime though, they’re Dates:
'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split.map { |s|
Date.new(*s.scan(/d+/).map(&:to_i) )
}
# => [#<Date: 1979-01-01 ((2443875j,0s,0n),+0s,2299161j)>,
# #<Date: 2012-03-29 ((2456016j,0s,0n),+0s,2299161j)>]
Breaking it down:
'DateTime.new(1979,1,1) DateTime.new(2012,3,29)'.split # => ["DateTime.new(1979,1,1)", "DateTime.new(2012,3,29)"]
.map { |s|
Date.new(
*s.scan(/d+/) # => ["1979", "1", "1"], ["2012", "3", "29"]
.map(&:to_i) # => [1979, 1, 1], [2012, 3, 29]
)
}
# => [#<Date: 1979-01-01 ((2443875j,0s,0n),+0s,2299161j)>,
# #<Date: 2012-03-29 ((2456016j,0s,0n),+0s,2299161j)>]
*
(AKA “splat”), used like this, explodes an array into its elements, which is useful when you have an array but the method only takes separate parameters.
The bigger question is why you’re getting values like that in a text file.
Are you passing the line into the function? Currently line would be undefined
You have a string
"DateTime.new(1979,1,1) DateTime.new(2012,3,29)"
? Why?This could well be an “XY Problem“. WHY do you have that line in a text file?