我有三个带有计数的日期数组:
first = [["July 01", "2"]["July 03", "2"]]
second = [["June 30", "2"]["July 01", "2"]["July 02", "2"]]
third = [["July 01", "2"]["July 02", "2"]]
我正在尝试(但没有成功)比较三个数组,获取完整的日期范围,并将结果为 0 的缺失数组注入(inject)到其他数组中...这样最终每个数组都会包含起始日期的条目6 月 30 日至 7 月 3 日,如下所示:
first = [["June 30", "0"]["July 01", "2"]["July 02", "0"]["July 03", "2"]]
second = [["June 30", "2"]["July 01", "2"]["July 02", "2"]["July 03", "0"]]
third = [["June 30", "0"]["July 01", "2"]["July 02", "2"]["July 03", "0"]]
我尝试了一系列非常复杂的比较(例如进行演绎,存储为新数组,然后使用该数组添加到缺失的数组,但是当有两个以上的数组要比较时,它会变得非常复杂)和注入(inject)来做到这一点,但我认为必须有一种相对简单的方法来使用 Ruby 或 Rails 来做到这一点。有什么想法吗?
最佳答案
这是另一种方法,使用日期
:
require 'date'
def compare_dates(*items)
all_dates = items.flatten(1).map { |d| Date.parse(d.first) }
str_dates = (all_dates.min..all_dates.max).map { |d| d.strftime("%B %d") }
items.map do |arr|
str_dates.map do |date|
current = arr.select { |e| e[0] == date }.flatten
current.empty? ? [date, "0"] : current
end
end
end
compare_dates(first, second, third)
#=> [[["June 30", "0"], ["July 01", "2"], ["July 02", "0"], ["July 03", "2"]],
# [["June 30", "2"], ["July 01", "2"], ["July 02", "2"], ["July 03", "0"]],
# [["June 30", "0"], ["July 01", "2"], ["July 02", "2"], ["July 03", "0"]]]
如果你想覆盖每个数组的值,你可以这样做:
first, second, third = compare_dates(first, second, third)
first
#=> [["June 30", "0"], ["July 01", "2"], ["July 02", "0"], ["July 03", "2"]]
second
#=> [["June 30", "2"], ["July 01", "2"], ["July 02", "2"], ["July 03", "0"]]
third
#=> [["June 30", "0"], ["July 01", "2"], ["July 02", "2"], ["July 03", "0"]]
关于ruby-on-rails - 在 Ruby 中比较数组时填充缺失的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45422701/