设置一个包含两列的数组?

时间:2011-02-13 20:18:28

标签: ruby-on-rails ruby ruby-on-rails-3

好的,我有这个红宝石

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">]

这会返回两个位置......很不错...... 一个位置有很多请求

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

这会返回所有承诺(这是一笔金额),这也很容易

 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]]

这几乎是一样的,但有日期......

我的问题是如何返回像这样的数组

 => [[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' ]]

基本上是同一数组中的承诺和日期的数组

2 个答案:

答案 0 :(得分:3)

您必须使用inject来避免嵌套数组:

Location.find_all_by_artist_name("SomeBand").inject([]) do |pairs,location|
  pairs.concat location.requests.map { |request| [request.created_at,request.pledge] }
end

答案 1 :(得分:1)

locations.map do |location| 
  location.requests.map { |r| [r.created_at, r.pledge] }
end.flatten(1).sort_by(&:first)