arr = [[["July 01", "2"], ["July 03", "2"]],
[["June 30", "2"], ["July 01", "2"], ["July 02", "2"]],
[["July 01", "2"], ["July 02", "2"]]]
require 'date'
default = arr.flatten(1).
map(&:first).
uniq.
sort_by { |s| Date.strptime(s, '%B %d') }.
product(['0']).
to_h
#=> {"June 30"=>"0", "July 01"=>"0", "July 02"=>"0", "July 03"=>"0"}
arr.map { |a| default.merge(a.to_h).to_a }
#=> [[["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"]]]
的步驟如下。
b = arr.flatten(1)
#=> [["July 01", "2"], ["July 03", "2"], ["June 30", "2"], ["July 01", "2"],
# ["July 02", "2"], ["July 01", "2"], ["July 02", "2"]]
c = b.map(&:first)
#=> ["July 01", "July 03", "June 30", "July 01", "July 02", "July 01", "July 02"]
d = c.uniq
#=> ["July 01", "July 03", "June 30", "July 02"]
e = d.sort_by { |s| Date.strptime(s, '%B %d') }
#=> ["June 30", "July 01", "July 02", "July 03"]
f = e.product(['0'])
#=> [["June 30", "0"], ["July 01", "0"], ["July 02", "0"], ["July 03", "0"]]
default = f.to_h
#=> {"June 30"=>"0", "July 01"=>"0", "July 02"=>"0", "July 03"=>"0"}
爲了計算
arr.map { |a| default.merge(a.to_h).to_a }
的arr
第一值被傳遞到塊和塊變量a
被設定爲等於該值,並且執行塊的計算。
a = arr.first
#=> [["July 01", "2"], ["July 03", "2"]]
g = a.to_h
#=> {"July 01"=>"2", "July 03"=>"2"}
h = default.merge(g)
#=> {"June 30"=>"0", "July 01"=>"2", "July 02"=>"0", "July 03"=>"2"}
h.to_a
#=> [["June 30", "0"], ["July 01", "2"], ["July 02", "0"], ["July 03", "2"]]
arr
其他值的計算是相似的。
計算d
參見Date::strptime。
乾淨,簡潔,美麗。謝謝格里。 – Ben