【问题标题】:Range operators in Ruby similar to PostgreSQLRuby 中类似于 PostgreSQL 的范围运算符
【发布时间】:2013-05-24 13:52:48
【问题描述】:

是否有 Ruby gem 可以实现类似于PostgreSQL does 的范围计算?尤其是与时间相关的范围函数?

【问题讨论】:

    标签: ruby-on-rails ruby datetime range date-range


    【解决方案1】:

    Range#cover? 用于测试对象是否在范围的开始和结束之间。

    Ruby 等价于'[2011-01-01,2011-03-01)'::tsrange @> '2011-01-10'::timestamp 是:

    (Date.new(2011,01,01)..Date.new(2011,03,01)).cover? Date.new(2011,01,10)
    # => true
    

    它测试Date.new(2011,01,01) <= Date.new(2011,01,10) <= Date.new(2011,03,01)

    【讨论】:

      【解决方案2】:

      如果不确切知道您要完成什么,很难回答这个问题,但您可能想查看 ActiveSupport gem 的 CoreExtensions 模块:http://guides.rubyonrails.org/active_support_core_extensions.html

      使用gem install activesupport 安装 ActiveSupport 或将其添加到您的 Gemfile。

      使用 ActiveSupport,您可以执行以下操作:

      require 'active_support/core_ext'
      
      10.days.from_now #=> 2013-06-08 08:37:34 -0400
      DateTime.now.beginning_of_year #=> Tue, 01 Jan 2013 00:00:00 -0400
      1.megabyte #=> 1048576
      (1..10).step(2) #=> [1, 3, 5, 7, 9]
      (1..10).overlaps?(0..7) #=> true
      Date.current.next_month #=> Sat, 29 Jun 2013
      Date.current.prev_week(:friday) #=> Fri, 24 May 2013
      

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2016-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多