Forum: Ruby sort_by different variables?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8e7e5b934fcbcdfb475072685755457f?d=identicon&s=25 Taylor Strait (taylorstrait)
on 2009-02-09 16:24
I have a user control panel that generates an event log by merging
various things that can happen on the site. These are:

user joins
user receives invitation
user completes invitation
user refers someone
user referee activates account

So I want to merge these events into a single array and sort them. It
works well sorting by created_at. However, I do not have unique classes
for all of the events I want to merge (yeah, REST would have worked well
here).  So when I populate the array I do this:

      # create array of all events for the log
      @events = []
      @events << @user.invitations
      @events << @user.pending_referrals
      @events << @user.active_referrals
      @events = @events.flatten!.sort_by {|x| x.created_at }.reverse

A pending_referral and active_referral are the same object,but pending
has an activated_at = nil and an active_referral has activated_at =
datetime.  So, it is possible to sort this array by created_at OR
activated_at?
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-02-09 17:52
(Received via mailing list)
2009/2/9 Taylor Strait <taylorstrait@gmail.com>:
> works well sorting by created_at. However, I do not have unique classes
> for all of the events I want to merge (yeah, REST would have worked well
> here).  So when I populate the array I do this:
>
>      # create array of all events for the log
>      @events = []
>      @events << @user.invitations
>      @events << @user.pending_referrals
>      @events << @user.active_referrals
>      @events = @events.flatten!.sort_by {|x| x.created_at }.reverse

First of all, I believe you want #concat and not #<<:

irb(main):003:0> a = []
=> []
irb(main):004:0> a << [1,2,3]
=> [[1, 2, 3]]
irb(main):005:0> a << [6,7,8]
=> [[1, 2, 3], [6, 7, 8]]
irb(main):006:0> a
=> [[1, 2, 3], [6, 7, 8]]

irb(main):007:0> a = []
=> []
irb(main):008:0> a.concat [1,2,3]
=> [1, 2, 3]
irb(main):009:0> a.concat [6,7,8]
=> [1, 2, 3, 6, 7, 8]
irb(main):010:0> a
=> [1, 2, 3, 6, 7, 8]

> A pending_referral and active_referral are the same object,but pending
> has an activated_at = nil and an active_referral has activated_at =
> datetime.  So, it is possible to sort this array by created_at OR
> activated_at?

arr.sort_by {|x| x.activated_at || x.created_at}

Kind regards

robert
8e7e5b934fcbcdfb475072685755457f?d=identicon&s=25 Taylor Strait (taylorstrait)
on 2009-02-09 17:53
Thanks a lot, Robert!
This topic is locked and can not be replied to.