Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoMethodError: undefined method `yesterday' for Date:Class

Tags:

date

ruby

Every answer posted on SO (yes, I checked) seems to have require 'date' as a solution. I've done that and my code still won't work.

require 'date'

yesterday = RepSched::Helpers.datestring(Date.yesterday)

For some reason, Ruby chokes on Date.yesterday

NoMethodError: undefined method `yesterday' for Date:Class

What am I doing wrong?

edit

Oh no! Now my problem is bigger than I thought. Now that I've realized that issue, I realize DateTime's behavior is different too!

like image 447
sent1nel Avatar asked Dec 08 '22 06:12

sent1nel


2 Answers

yesterday is provided by Rails / Active Support. You can either require it in your non-Rails project:

require 'active_support/core_ext/date/calculations'

Date.yesterday
#=> #<Date: 2014-09-02 ((2456903j,0s,0n),+0s,2299161j)>

Or calculate it yourself:

require 'date'

Date.today - 1
#=> #<Date: 2014-09-02 ((2456903j,0s,0n),+0s,2299161j)>
like image 132
Stefan Avatar answered Jan 13 '23 23:01

Stefan


Rails can be a bit of a pain because it adds new methods to Date which surprises many newcomers to Ruby. You can get yesterday, without using Rails by doing:

$ pry
[1] pry(main)> require 'date'
=> false
[2] pry(main)> Date.today
=> #<Date: 2014-09-03 ((2456904j,0s,0n),+0s,2299161j)>
[4] pry(main)> Date.today - 1
=> #<Date: 2014-09-02 ((2456903j,0s,0n),+0s,2299161j)>
like image 44
David Weiser Avatar answered Jan 13 '23 23:01

David Weiser