Skip to content

Instantly share code, notes, and snippets.

@pushcx
Created February 13, 2016 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pushcx/685dc83de087e137bf85 to your computer and use it in GitHub Desktop.
Save pushcx/685dc83de087e137bf85 to your computer and use it in GitHub Desktop.
Transaction = Struct.new(:amount, :parent)
t1 = Transaction.new 1, nil
t2 = Transaction.new 2, t1
t3 = Transaction.new 4, t2
t4 = Transaction.new 8, nil
TransactionEnumerator = Struct.new(:ary) do
include Enumerable
def each
ary.each do |t|
yield t
yield t while t = t.parent
end
end
end
ts = TransactionEnumerator.new [t3, t4]
puts ts.inject(0) { |total, transaction| total + transaction.amount }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment