使用Ruby在日期范围之间选择数组

时间:2014-02-02 04:39:36

标签: ruby arrays

我有一个数组数组,我想选择日期落在一定范围内的数组。

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-242014-01-29之间获取所有数组。

3 个答案:

答案 0 :(得分:4)

不使用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) }

请注意,这取决于以年 - 月 - 日订单表示的日期。

编辑:我之前使用的是我认为的Range#include?,但是@ toro2k指出实际上是Enumerable#include?,这很慢。我原以为Range#include?只能比较端点,因为<=>是为字符串定义的。不是这样;它仅适用于值为数字或单个字符串的情况(否则为superEnumerable#include?)。那让我很困惑。对于任何有兴趣的人,我想我现在明白限制申请的原因。

我们希望('aa'..'zz').include?('mno')的行为与

相同
('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?只考虑了端点,

('aa'..'zz').include?("mno") # => true

答案 1 :(得分:2)

require 'date'
range = Date.parse("2014-01-24")..Date.parse("2014-01-29")
ar.select { |x| range.include?(Date.parse(x[1])) }
=> [[41778, "2014-01-24"],
 [34182, "2014-01-25"],
 [58869, "2014-01-26"],
 [72162, "2014-01-27"],
 [43677, "2014-01-28"],
 [37980, "2014-01-29"]]

答案 2 :(得分:2)

我会使用Comparable#between?

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"]
     ]

ar.select { |_,e| e.between?("2014-01-24","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"]]