在ruby中合并2个不同的数组

时间:2016-04-03 12:25:29

标签: arrays ruby merge

我想合并两个内部有不同数据的数组。

这是第一个阵列:

[
 [Wed, 30 Mar 2016, 2],
 [Fri, 01 Apr 2016, 1],
 [Sat, 02 Apr 2016, 1],
 [Sun, 03 Apr 2016, 1]
]

这是第二个数组:

[
 Sun, 27 Mar 2016,
 Mon, 28 Mar 2016,
 Tue, 29 Mar 2016,
 Wed, 30 Mar 2016,
 Thu, 31 Mar 2016,
 Fri, 01 Apr 2016,
 Sat, 02 Apr 2016,
 Sun, 03 Apr 2016
]

结果我想:

[
 Sun, 27 Mar 2016=>0,
 Mon, 28 Mar 2016=>0,
 Tue, 29 Mar 2016=>0,
 Wed, 30 Mar 2016=>2,
 Thu, 31 Mar 2016=>0,
 Fri, 01 Apr 2016=>1,
 Sat, 02 Apr 2016=>0,
 Sun, 03 Apr 2016=>1
]

最后,这是拥有2个数组的代码

    @last_7_days = Statistic.where("date(created_at) > ?", 7.days.ago).group("date(created_at)").count
    @last_days = Date.today.downto(Date.today - 7.days).reverse_each.collect{|m| m}

2 个答案:

答案 0 :(得分:3)

a = [
  ["Wed, 30 Mar 2016", 2],
  ["Fri, 01 Apr 2016", 1],
  ["Sat, 02 Apr 2016", 1],
  ["Sun, 03 Apr 2016", 1]
]

b = [
  "Sun, 27 Mar 2016",
  "Mon, 28 Mar 2016",
  "Tue, 29 Mar 2016",
  "Wed, 30 Mar 2016",
  "Thu, 31 Mar 2016",
  "Fri, 01 Apr 2016",
  "Sat, 02 Apr 2016",
  "Sun, 03 Apr 2016"
]

Hash[b.map { |s| [s,0] }].merge(Hash[a])
  #=> {"Sun, 27 Mar 2016"=>O,
  "Mon, 28 Mar 2016"=>O,
  "Tue, 29 Mar 2016"=>O,
  "Wed, 30 Mar 2016"=>2,
  "Thu, 31 Mar 2016"=>O,
  "Fri, 01 Apr 2016"=>1,
  "Sat, 02 Apr 2016"=>1,
  "Sun, 03 Apr 2016"=>1
}

答案 1 :(得分:0)

以下是一个例子:

sample1 = [1,2,3,4]
sample2 = [5,6,7,8]

sample1.push(sample2)

输出:

[1, 2, 3, 4, [5, 6, 7, 8]]