Skip to content

Instantly share code, notes, and snippets.

@domgetter
Last active February 13, 2016 14:17
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 domgetter/3ac0563071d44898cd92 to your computer and use it in GitHub Desktop.
Save domgetter/3ac0563071d44898cd92 to your computer and use it in GitHub Desktop.
class Transaction
attr_accessor :amount, :parent
def initialize(amount, parent)
self.amount = amount
self.parent = parent
end
def each
# while there are parent transactions, keep yielding them
current_transaction = self
yield current_transaction
while current_transaction.parent
current_transaction = current_transaction.parent
yield current_transaction
end
end
include Enumerable
end
t1 = Transaction.new(100, nil)
t2 = Transaction.new(250, t1)
t3 = Transaction.new(300, t2)
current = t3
current.inject(0) {|total, tr| total + tr.amount}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment