日期范围红宝石之间的选择数组 [英] Select arrays between date ranges with Ruby

查看:135
本文介绍了日期范围红宝石之间的选择数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组的数组,我想与在一定范围内下降的日期选择阵列。

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年1月24日 2014年1月29日

推荐答案

如果不使用日期

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) }

请注意这取决于日期是在年 - 月 - 天阶前pressed。

Note this depends on the date being expressed in year-month-day order.

编辑:我以前用了我认为的#范围包括哪些?,但@ toro2k指出,就是实际上的可枚举#包括?,这是相当缓慢。我原以为范围#包括将能够只比较端点,因为&LT; =&GT; 定义弦乐。事实并非如此;当值是数字或单个字符的字符串它只适用(否则它超级 s到可枚举#包括哪些内容?)。这使我迷惑不解。任何有兴趣,我想我现在明白了限制应用程序的原因。

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 supers to Enumerable#include?). That puzzled me. For anyone interested, I think I now understand the reason for the restricted application.

我们希望('AA'..'ZZ')。包括什么呢?('MNO')来表现一样​​

We would want ('aa'..'zz').include?('mno') to behave the same as

('aa'..'zz').to_a.include?('mno') => false

假设我们做到这一点:

Suppose we do this:

class String
  alias :spaceship :<=>
  def <=>(other)
    spaceship(other.size > 1 ? other[0,2] : other)
  end
end

然后

"mno" >= 'aa' # => true
"mno" <= 'zz' # => true

因此​​,如果#范围包括哪些?只考虑终点,

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

这篇关于日期范围红宝石之间的选择数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆