开发者

Ruby: Sorting an array that is "linked" to another array

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开发者_StackOverflow社区 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?


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜