0

Ok so I have this ruby

l = Location.find_all_by_artist_name("SomeBand")
=> [#<Location id: 1, venue: "Knebworth - Stevenage, United Kingdom", showdate: "2011-07-01", created_at: "2011-01-01 18:14:08", updated_at: "2011-01-01 18:14:08", band_id: nil, artist_name: "SomeBand">, 
  #<Location id: 2, venue: "Empire Polo Club - Indio, United States", showdate: "2011-04-23", created_at: "2011-02-10 02:22:08", updated_at: "2011-02-10 02:22:08", band_id: nil, artist_name: "SomeBand">]

This returns two locations..easy enough right... A location has many requests

l.collect{|location| location.requests.map(&:pledge) }
=> [[nil, nil, nil, #<BigDecimal:103230d58,'0.1E2',9(18)>, #<BigDecimal:103230a10,'0.1E2',9(18)>], [nil, nil]]

this returns all the pledges (which is a dollar amount) and thats easy enough as well

 l.collect{|location| location.requests.map(&:created_at) }
 => [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, Sun, 09 Jan 2011 18:34:19 UTC +00:00, Sun, 09 Jan 2011 18:38:48 UTC +00:00, Sun, 09 Jan 2011 18:51:10 UTC +00:00, Sun, 09 Jan 2011 18:52:30 UTC +00:00], [Thu, 10 Feb 2011 02:22:08 UTC +00:00, Thu, 10 Feb 2011 20:02:20 UTC +00:00]]

this does almost the same thing but with dates.....

My problem is how do i return an array like this

 => [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, nil ][Sun, 09 Jan 2011 18:34:19 UTC +00:00, nil ][ Sun, 09 Jan 2011 18:38:48 UTC +00:00, nil ][ Sun, 09 Jan 2011 18:51:10 UTC +00:00, #<BigDecimal:103230d58,'0.1E2' ]]

Basically an array of both the pledge and the date in the same array

0

2 Answers 2

3

You have to use inject to avoid nested arrays:

Location.find_all_by_artist_name("SomeBand").inject([]) do |pairs,location|
  pairs.concat location.requests.map { |request| [request.created_at,request.pledge] }
end
Sign up to request clarification or add additional context in comments.

7 Comments

+1 for inject. It is the basis for a lot of other methods but is not glamorous so people ignore it.
Thanks @Jordon ...what does inject do anyways...this works great
inject works much like map. Instead of just pushing the result of the given block to an Array, you have to tell it what do in your bock. The given block takes an accumulator (pairs above) and a single element from the array. The block has to return the accumulator each time, which is what pairs.concat does. The accumulator is initially set to the value you passed inject ([] above). At the end, it returns the final value of the accumulator.
Is there a way to order the inner arrays by the request.created_at
@Matt: being the sorting key the first element: unsorted.sort_by(&:first)
|
1
locations.map do |location| 
  location.requests.map { |r| [r.created_at, r.pledge] }
end.flatten(1).sort_by(&:first)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.