Ruby Arrays and Hashes and Days of the Week.

I was playing around with different ways to represent the days of the week and their index from 0 to 6 as hashes and arrays.  Here’s what I cam up with:

irb(main):001:0> require 'date'
=> true

irb(main):002:0> Date::DAYNAMES
=> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

irb(main):003:0> Date::DAYNAMES.enum_with_index.to_a
=> [["Sunday", 0], ["Monday", 1], ["Tuesday", 2], ["Wednesday", 3], ["Thursday", 4], ["Friday", 5], ["Saturday", 6]]

irb(main):004:0> Date::DAYNAMES.enum_with_index.to_a.map{|a| a.reverse}
=> [[0, "Sunday"], [1, "Monday"], [2, "Tuesday"], [3, "Wednesday"], [4, "Thursday"], [5, "Friday"], [6, "Saturday"]]

irb(main):005:0> Hash[*Date::DAYNAMES.enum_with_index.to_a.flatten]
=> {"Friday"=>5, "Wednesday"=>3, "Saturday"=>6, "Tuesday"=>2, "Monday"=>1, "Sunday"=>0, "Thursday"=>4}

irb(main):006:0> Hash[*Date::DAYNAMES.enum_with_index.to_a.flatten].invert
=> {5=>"Friday", 0=>"Sunday", 6=>"Saturday", 1=>"Monday", 2=>"Tuesday", 3=>"Wednesday", 4=>"Thursday"}

Leave a Reply

Your email address will not be published. Required fields are marked *