views:

38

answers:

2

In my rails app, I have a loop in my controller that does this:

event_prices = []
event_dates = []
for event in @customer.events
  event_prices.push(event.total_prices)
  event_dates.push(event.event_time.strftime("%b %d, %Y at %I%p"))
end

I then use the arrays to push data into a highcharts graph. What I want to do is sort the event_dates array in order, but if I do that, I'll lose the order of the event_prices. Right now, the event_price[1] corresponds to event_dates[1] and so on, but if I call a sort! on event_dates, it won't sort event_prices along with it.

So how can I get it so that I sort both arrays the same way?

+1  A: 

How about something like:

event_prices = []
event_dates = []
@customer.events.sort_by { |e| e.event_time }.each do |event|
  event_prices << event.total_prices
  event_dates << event.event_time.strftime("%b %d, %Y at %I%p")
end
thenduks
Wow, you are a ruby wizard :)Thanks
Reti
Btw this will by default sort them oldest to newest. To get the reverse you could just reverse the list, or alternatively save off the current date `now = Time.now` and then make the block to `sort_by` like so: `now - e.event_time`.
thenduks
Thanks again. I actually want oldest to newest, so this is great :)
Reti
No problem. Let me know if you have a problem... just in case I fat-fingered it. Also keep in mind that you can do this through your association (as in `@customer.events(...)` or using named scopes like defining `@customer.ordered_events`) but this might not be a big deal for your use-case. Take a look at the active record association docs.
thenduks
For named scope, try starting here: http://railscasts.com/episodes/108-named-scope
thenduks
A: 

It's better to use DB for sorting. I would do the following:

event_prices, event_dates = 
  @customer.events(:order => "event_time ASC").map do |e|
    [e.total_prices, e.event_time.strftime("%b %d, %Y at %I%p")]
  end.transpose
KandadaBoggu