Rails, Ruby, how to sort an Array?

后端 未结 6 1551
忘了有多久
忘了有多久 2021-01-31 07:13

in my rails app I\'m creating an array like so:

@messages.each do |message|

  @list << {
    :id => message.id,
    :title => message.title,
    :ti         


        
6条回答
  •  萌比男神i
    2021-01-31 07:56

     @list.sort_by{|e| e[:time_ago]}
    

    it defaults to ASC, however if you wanted DESC you can do:

     @list.sort_by{|e| -e[:time_ago]}
    

    Also it seems like you are trying to build the list from @messages. You can simply do:

    @list = @messages.map{|m| 
      {:id => m.id, :title => m.title, :time_ago => m.replies.first.created_at }
    }
    

提交回复
热议问题