reduce sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Order | |
attr_accessor :type, :sub_orders | |
def initialize type | |
self.type = type | |
self.sub_orders = [] | |
end | |
# 统计订单及其包含子订单的数量,按照订单类型归类 | |
def count_items | |
result = sub_orders.reduce({}) do |result, order| | |
order.count_items.each do |key, value| | |
result[key] = (result[key]||0) + value | |
end | |
result | |
end | |
result[type] = (result[type]||0) + 1 | |
result | |
end | |
def count_items2 | |
sub_orders.reduce({ type => 1 }) do |result, order| | |
order.count_items2.reduce(result) do |s, (key, value)| | |
s.update key => (s[key]||0) + value | |
end | |
end | |
end | |
end | |
orders = (0...10).map{|i| Order.new (i+65).chr.to_s} | |
orders[0].sub_orders = orders[1..3] | |
orders[2].sub_orders = orders[4..6] | |
orders[6].sub_orders = orders[7..9] | |
orders[9].sub_orders = orders[10..10] | |
orders.each do |o| | |
puts "#{o.type}: #{o.sub_orders.map(&:type).join(',')}" | |
end | |
puts orders[0].count_items | |
puts orders[0].count_items2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment