Created
June 12, 2011 12:11
-
-
Save monzou/1021492 to your computer and use it in GitHub Desktop.
Enumerable
This file contains hidden or 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 Account | |
attr_accessor :name, :balance | |
def initialize(name, balance) | |
@name = name | |
@balance = balance | |
end | |
def <=>(other) | |
@balance <=> other.balance | |
end | |
end | |
class Portfolio | |
include Enumerable | |
def initialize | |
@accounts = [] | |
end | |
def each(&block) | |
@accounts.each(&block) | |
end | |
def add_account(account) | |
@accounts << account | |
end | |
end | |
portfolio = Portfolio.new | |
portfolio.add_account Account.new("account1", 100) | |
portfolio.add_account Account.new("account2", 200) | |
portfolio.add_account Account.new("account3", 300) | |
puts portfolio.any? { |account| account.balance > 200 } | |
puts portfolio.all? { |account| account.balance > 100 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment