简体   繁体   中英

Check if the value is in range between closest array's elements. (ruby)

I need to know how would I check if my given value is between two closest array's members. For example I have an array of dates with the date of week start in given period of time. And I need to check if my given date is in one of its week. For example:

  1. 2015-11-02
  2. 2015-11-09
  3. 2015-11-16
  4. 2015-11-23

And my given value is 2015-11-11 for example. How should I check if it is one of these weeks date? Thanks for help.

%w(2015-11-02 2015-11-09 2015-11-16 2015-11-23).any? do |date| 
  date.to_date.cweek == Date.today.cweek
end

And here is what this does: First, you have an array of strings, you use any? to loop through it and check if any fulfils a requirement, then you cast you date strings into actual dates, and cweek gives you the number of a week in the year. Date.today gives you today's date.

Instead of Date.today.cweek you can use '2015-11-11'.to_date.cweek .

The loop above returns boolean; you could also get an array of values that fulfil a condition like this:

new_array = %w(2015-11-02 2015-11-09 2015-11-16 2015-11-23).map do |date| 
  date.to_date.cweek == '2015-11-11'.to_date.cweek
end.compact

Resources:


UPDATE

If you want to get from the database only records with a date from particular week, this is how you could do it:

my_date = '2015-11-11'.to_date
matching_records = MyResource.where( date: my_date.beginning_of_week..my_date.end_of_week )

The assumptions are that you have a model MyResource , and that it has a column date . What this does is returns a relation with all the records that have dates from the same week as my_date .

假设您的日期数组已排序:

date >= dates.first && date <= dates.last

If you're dealing with strings, you can "require 'date'" and transform your strings to dates ("Date.parse('2001-02-03')").

As others have suggested, you can then see if your date is between the first and last entry of your list.

If the real list is sorted and each entry is one week apart, then you can easily find where in the list your guy is.

Eg, say the list is [date_0, date_1, date_2, ..., date_k] (all 1 week apart), and you're given a test_date between date_0 and date_k. Then (test_date.jd - date_0.jd)/7 gives you the index of the date in your list that is <= test_date.

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