简体   繁体   中英

Ruby return only date older than 2 days ago - undefined method `days' for 2:Integer

I array below I want to get only days which are older than 2.days.ago

data = ["2020-02-21T07:52:14.114+0100",
 "2020-02-19T13:20:50.539+0100",
 "2020-02-11T12:36:16.565+0100",
 "2020-02-17T20:06:53.312+0100",
 "2020-02-04T09:42:30.754+0100",
 "2020-01-29T13:46:16.033+0100",
 "2020-02-18T11:15:12.894+0100"]

I'm trying to do this with code below:

data.select { |data| data if DateTime.parse(data) > 2.days.ago }

But I'm getting an error:

NoMethodError: undefined method `days' for 2:Integer

As others already pointed out in the comments, n.days.ago is not part of plain Ruby but is introduced with Ruby on Rails (see docs about days and ago ).

The equivalent to n.day.ago in plain Ruby might be something like this:

 Time.now - n * 24 * 60 * 60

That means when you want to select dates that are older than 2 days then you can write your example like this:

 two_days_ago = Time.now - 2 * 24 * 60 * 60
 data.select { |data| Time.parse(data) < two_days_ago }

Please note there is no need for the date if part in the select block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM