Malcolm Isaacson Malcolm Isaacson - 24 days ago 11
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
16.04.2017;Easter
25.12.2017;Christmas


(Sidenote: dates are formatted as dd.mm.yyyy)

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[*File.read('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 = File.read('holidays.txt').split(/\n/).map do |row| 
  date, holiday_name = row.split(';') 
  date = Date.parse(date, '%d.%m.%Y')
  [date, holiday_name]
end.to_h
=> {
  #<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"
}