Malcolm Isaacson Malcolm Isaacson - 5 months ago 55
Ruby Question

[ruby]Get file, parse text and create date object

I have a raw .txt file formatted as such:

01.01.2017;New Year

(Sidenote: dates are formatted as

I'm trying to read this file, slice the text per line and make a hash out of it, with the key being the date, and its value the name of the corresponding public holiday.

I've already gotten so far:

holidays = Hash[*'holidays.txt').split(/;|\n/)]

This results in the dates being set as strings, not date objects.

Any ideas as to how I could then transform these strings to Date (or DateTime) objects?

P.S.: I'm only using Ruby, so no Rails helpers...

Answer Source

Something like this

holidays ='holidays.txt').split(/\n/).map do |row| 
  date, holiday_name = row.split(';') 
  date = Date.parse(date, '%d.%m.%Y')
  [date, holiday_name]
=> {
  #<Date: 2017-01-01 ((2457755j,0s,0n),+0s,2299161j)> => "New Year",
  #<Date: 2017-04-16 ((2457860j,0s,0n),+0s,2299161j)> => "Easter",
  #<Date: 2017-12-25 ((2458113j,0s,0n),+0s,2299161j)> => "Christmas"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download