【问题标题】:Rails combine 4 arrays and sort the resulting array by "created_at"Rails 组合了 4 个数组并按“created_at”对结果数组进行排序
【发布时间】:2013-10-03 15:42:10
【问题描述】:

所以我试图组合 4 个不同项目的数组,然后按“created_at”列对这些数组进行排序,就像最新的一样。因此,结果数组应该是所有这些项目的排序数组,以便最新的项目是第一个,无论它们是什么类型。我可以对它进行排序,以便最新的项目,但它对每种类型的项目进行排序,然后开始对另一种类型进行排序。

例如:类型是衬衫和裤子。我在晚上 10:00 上传一件衬衫,然后在晚上 10:15 上传一件裤子,然后在晚上 10:30 上传一件衬衫。数组应该像 (shirt(10:30), pant(10:15), shirt(10:00)) 但我得到的是 (shirt(10:00), shirt(10:30), pant(10 :15))

这是我的代码:

@tops = Top.first(15)
@bottoms = Bottom.first(15)
@footwears = Footwear.first(15)
@accs = Accessory.first(15)

@tempItems = []
@temp = []
@temp = @tempItems + @tops 
@temp = @temp + @bottoms 
@temp = @temp + @footwears 
@temp = @temp + @accs

@temp.sort_by{ |temp| - temp.created_at.to_i}
@itemss = @temp.first(15)

【问题讨论】:

    标签: ruby-on-rails arrays sorting


    【解决方案1】:

    您需要将排序后的数组分配回@temp

    ...

    @temp =  @temp.sort_by{ |temp| - temp.created_at.to_i}
    

    【讨论】:

    • 谢谢。不知道我怎么没看到。
    【解决方案2】:

    你可以通过去掉不必要的赋值代码来减少混淆:

    fifteen= [Top, Bottom, FootWear, Accessory].
      flat_map{ |c| c.first(15) }.
      sort_by{ |e| -e.created_at.to_i }.
      first(15)
    

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 2011-09-21
      • 1970-01-01
      • 2016-01-06
      • 2020-11-21
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多