Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails - Convert Integer to Day of Week

I know you can use wday to return the day of the week as an integer value:

 Date.new(2001,2,3).wday           #=> 6 (a.k.a. "Saturday")

But, is there a method to do this the opposite way, in reverse?

Like:

 day_of_week(6)                        #=> "Saturday"

Or is this something I would convert on my own?

Thanks.

like image 973
Dodinas Avatar asked Jan 18 '14 01:01

Dodinas


2 Answers

The Date::DAYNAMES array has that information:

Date::DAYNAMES[6]
# => "Saturday"
like image 53
tlehman Avatar answered Sep 20 '22 09:09

tlehman


I would use a proc or lambda because I wouldn't want to type this Date::DAYNAMES[d] repeatedly.

day = Proc.new { |d| Date::DAYNAMES[d] }
day.call(6)
# => "Saturday"

Or even more succinct as a lambda:

day = ->num { Date::DAYNAMES[num] }
day.(6)
# => "Saturday"

Just remember to: require 'Date'

like image 28
MrPizzaFace Avatar answered Sep 19 '22 09:09

MrPizzaFace