English 中文(简体)
如何在Ruby(不是铁路)中按日期排序?
原标题:How to sort_by date in Ruby (not Rails)?
  • 时间:2012-05-25 14:25:53
  •  标签:
  • ruby

我知道铁路公司将分解方法 建在积极记录中 但我正在写一个普通的红宝石脚本 希望能按日期从阵列中排序记录

日期将存储在多维阵列的一个单元格中。

我最能用什么方法处理这个问题? 这样我就可以到达我所做的 sort_by_date 的地步,我指的就是 ASC DESC ?

我不必使用 sort_by_date 的方法,但我想在收藏中轻而易举地调用一种方法,获取我想要的结果。

思念?

最佳回答

像这样吗?

  class Array
    def sort_by_date(direction="ASC")
      if direction == "ASC"
        self.sort
      elsif direction == "DESC"
        self.sort {|a,b| b <=> a}
      else
        raise "Invalid direction. Specify either ASC or DESC."    
      end
    end
  end

多维数组只是一系列数组,所以将这种方法调用在您想要排序的维度上。

问题回答
def sort_by_date(dates, direction="ASC")
  sorted = dates.sort
  sorted.reverse! if direction == "DESC"
  sorted
end

我现在这样做的方式是:

@collection.sort! { |a,b|  DateTime.parse(a[ date ]) <=> DateTime.parse(b[ date ]) }

使用“! ” 运算符时, 我正影响着同一个变量( 否则我还需要另一个变量来控制修改后的变量 ) 。 到目前为止, 它一直是一个符咒。

以下对象可能不会为 DateTime 对象工作, 但应为 DateTime 对象工作。 这是因为 DateTime 对象可以转换成整数 。

我最近不得不做一个降级类的 日期时间天体, 这就是我想出来的。

def sort_by_datetime(dates, direction="ASC")
  dates.sort_by { |date| direction == "DESC" ? -date.to_i : date }
end

我用的是旧版的铁路和 rabl rabl ,对我有用

collection @name_of_your_collection.sort! { |a,b|  DateTime.parse(a[ start_at ]) <=> DateTime.parse(b[ start_at ]) }
node do |s|
 # lots of attributes
  s
end




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签