通过updated_at对ruby数组进行排序

时间:2021-01-20 15:59:46

all I want to do, is to fetch the lastest item from my models and have them in an array sorted (freshest items first) by the attribute "updated_at".

我想要做的就是从我的模型中获取最新的项目,然后通过属性“updated_at”对它们进行排序(最新的项目)。

Somewhere is an error, but I can't find it:

某处是错误,但我找不到它:

  @results = Array.new
  Note.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
      @results << item
  end

  Picture.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
    @results << item
  end


  @results = @results.sort_by{ |result| result.updated_at}

3 个解决方案

#1


You need to do the comparison in the sort. `

您需要在排序中进行比较。 `

  @results = Array.new
  Note.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
      @results << item
  end

  Picture.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
    @results << item
  end
  @results.sort!{|a,b|a.updated_at <=> b.updated_at}

This will sort the @results array in place.

这将对@results数组进行排序。

#2


notes    = Note.find    :all, :limit => 3, :order => "created_at DESC"
pictures = Picture.find :all, :limit => 3, :order => "created_at DESC"
@results = (notes + pictures).sort_by(&:updated_at)

#3


Maybe not as terse, or readable, but it is a little DRYer. I can't convince myself this is better than weppos's answer. I do like replacing "Class.find :all" with just "Class.all".

也许不是简洁或可读,但它有点干。我无法说服自己这比weppos的回答更好。我喜欢用“Class.all”替换“Class.find:all”。

results = [Note, Picture].inject([]) do |memo, clazz|
  memo + clazz.all(:limit => 3, :order => "created_at DESC")
end
results = results.sorted_by(&:updated_at)

#1


You need to do the comparison in the sort. `

您需要在排序中进行比较。 `

  @results = Array.new
  Note.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
      @results << item
  end

  Picture.find(:all, :limit => 3, :order => "created_at DESC").each do |item|
    @results << item
  end
  @results.sort!{|a,b|a.updated_at <=> b.updated_at}

This will sort the @results array in place.

这将对@results数组进行排序。

#2


notes    = Note.find    :all, :limit => 3, :order => "created_at DESC"
pictures = Picture.find :all, :limit => 3, :order => "created_at DESC"
@results = (notes + pictures).sort_by(&:updated_at)

#3


Maybe not as terse, or readable, but it is a little DRYer. I can't convince myself this is better than weppos's answer. I do like replacing "Class.find :all" with just "Class.all".

也许不是简洁或可读,但它有点干。我无法说服自己这比weppos的回答更好。我喜欢用“Class.all”替换“Class.find:all”。

results = [Note, Picture].inject([]) do |memo, clazz|
  memo + clazz.all(:limit => 3, :order => "created_at DESC")
end
results = results.sorted_by(&:updated_at)