[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

sort_by different variables?

Taylor Strait

2/9/2009 3:24:00 PM

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?
--
Posted via http://www.ruby-....

2 Answers

Robert Klemme

2/9/2009 4:50:00 PM

0

2009/2/9 Taylor Strait <taylorstrait@gmail.com>:
> 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

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

--
remember.guy do |as, often| as.you_can - without end

Taylor Strait

2/9/2009 4:53:00 PM

0

Thanks a lot, Robert!
--
Posted via http://www.ruby-....