Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Rails Weekday indexes different than Ruby's?

in Rails 3.0.10

ruby-1.9.2-p180 :010 > Time::DAYS_INTO_WEEK
 => {:monday=>0, :tuesday=>1, :wednesday=>2, :thursday=>3, :friday=>4, :saturday=>5, :sunday=>6} 

And

ruby-1.9.2-p180 :011 > Date.today
 => Mon, 10 Oct 2011 
ruby-1.9.2-p180 :012 > Date.today.wday
 => 1 

So, Monday is 0 in the Time mapping, and 1 in the Date mapping.
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/time/calculations.rb

I feel like starting with Sunday as zero is the safer, more common, more likely to be understood by someone else way to do things. I was hoping to understand the history / reasoning in case I overlook something.

My use case: I'm storing day of week explicitly in my db. I figured storing as an integer would be more efficient and easier to work with than storing "Monday", "Tuesday", etc.

PS I had the great idea to do something like the following. Map back and forth from weekday strings inside methods (hiding the integer).

ruby-1.9.2-p180 :010 > Time::DAYS_INTO_WEEK
 => {:monday=>0, :tuesday=>1, :wednesday=>2, :thursday=>3, :friday=>4, :saturday=>5, :sunday=>6} 
Time::DAYS_INTO_WEEK[day_of_week.downcase.to_sym]
Time::DAYS_INTO_WEEK.to_a.select{|k, v| v == start_day }.first.first.to_s.capitalize
like image 374
John Hinnegan Avatar asked Oct 10 '11 20:10

John Hinnegan


1 Answers

I'm not sure there is a absolutely correct answer to this question. I think Zabba was onto something regarding the difference between how days of weeks are numbered in the US/Canada and Internationally.

Regarding historical reasoning, it looks like David Heinemeier Hansson (DHH) made the following commit on February 21, 2005: https://github.com/rails/rails/commit/25f8a25c3ea107dcd0688307ac0ce19c4306f6b4

The commit message clearly states that it was intentional to make beginning of week be a Monday and not a Sunday. Considering that David is opinionated, the creator of Rails, and was still living in Denmark at the time, it sort of makes sense that he'd ignore the fact that Ruby's Date and Time classes consider Sunday day 0.

(later commit 1c5a6944d38e6818d254f272057b513b038b2270 moved days_into_week into the constant you see now DAYS_INTO_WEEK; and later the same constant was added to the Date class in commit bc1bcddede0c300e9c88f76a66a152814b734981).

like image 95
Ryan Sandridge Avatar answered Nov 15 '22 20:11

Ryan Sandridge