Skip to content

Instantly share code, notes, and snippets.

@fsword
Created August 27, 2013 13:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fsword/6353526 to your computer and use it in GitHub Desktop.
reduce sample
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