Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Convert Day Of Week To Integer

How would you convert a day string (i.e. "Monday" or "Wednesday"), into the corresponding wday integer (1 or 3)?

I've come up with this convoluted way

Date.today.beginning_of_week("Monday".downcase.to_sym).wday
like image 224
Abundance Avatar asked Nov 20 '18 14:11

Abundance


1 Answers

You can parse it using strptime:

Date.strptime('Monday', '%A').wday
#=> 1

Date.strptime('Wednesday', '%A').wday
#=> 3

The intermediate date object refers to the weekday in the current week:

Date.today
#=> #<Date: 2018-11-20 ...>

Date.strptime('Monday', '%A')
#=> #<Date: 2018-11-19 ...>

You can also use _strptime (prefixed with an underscore) to extract the date elements which happen to be :wday for a single weekday:

Date._strptime('Monday', '%A')
#=> {:wday=>1}
like image 100
Stefan Avatar answered Nov 09 '22 20:11

Stefan