-
-
Save domgetter/3ac0563071d44898cd92 to your computer and use it in GitHub Desktop.
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 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