使用 Ruby 在日期范围之间选择数组 [英] Select arrays between date ranges with Ruby
问题描述
我有一个数组数组,我想选择日期落在某个范围内的数组.
I have an array of arrays, I want to select arrays with a date that falls in a certain range.
ar = [[72162, "2014-01-21"],
[53172, "2014-01-22"],
[49374, "2014-01-23"],
[41778, "2014-01-24"],
[34182, "2014-01-25"],
[58869, "2014-01-26"],
[72162, "2014-01-27"],
[43677, "2014-01-28"],
[37980, "2014-01-29"],
[87354, "2014-01-30"],
[43677, "2014-01-31"]]
例如,我想获取 2014-01-24
和 2014-01-29
之间的所有数组.
For example, I'd like to get all arrays between 2014-01-24
and 2014-01-29
.
推荐答案
不使用Date
:
ar.select { |_,d| d >= "2014-01-24" && d <= "2014-01-29" }
=> [[41778, "2014-01-24"],
[34182, "2014-01-25"],
[58869, "2014-01-26"],
[72162, "2014-01-27"],
[43677, "2014-01-28"],
[37980, "2014-01-29"]]
或
ar.select { |_,d| ("2014-01-24".."2014-01-29").cover?(d) }
请注意,这取决于以年-月-日顺序表示的日期.
Note this depends on the date being expressed in year-month-day order.
我以前使用过我认为是 Range#include?,但@toro2k 指出这实际上是 Enumerable#include?,这很慢.我原以为 Range#include?
只能比较端点,因为 <=>
是为字符串定义的.不是这样;它仅适用于值是数字或单个字符串时(否则 super
到 Enumerable#include?
).这让我很困惑.对于任何有兴趣的人,我想我现在明白限制申请的原因了.
I formerly used what I thought was Range#include?, but @toro2k pointed out that is was actually Enumerable#include?, which is quite slow. I had thought that Range#include?
would be able to just compare endpoints, since <=>
is defined for Strings. Not so; it only applies when the values are numeric or single character strings (else it super
s to Enumerable#include?
). That puzzled me. For anyone interested, I think I now understand the reason for the restricted application.
我们希望 ('aa'..'zz').include?('mno')
的行为与
We would want ('aa'..'zz').include?('mno')
to behave the same as
('aa'..'zz').to_a.include?('mno') => false
假设我们这样做:
class String
alias :spaceship :<=>
def <=>(other)
spaceship(other.size > 1 ? other[0,2] : other)
end
end
然后
"mno" >= 'aa' # => true
"mno" <= 'zz' # => true
所以如果 Range#include?
只考虑端点,
so if Range#include?
only considered the endpoints,
('aa'..'zz').include?("mno") # => true
这篇关于使用 Ruby 在日期范围之间选择数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!