Skip to content

Instantly share code, notes, and snippets.

@geckofu
Last active August 29, 2015 14:19
Show Gist options
  • Save geckofu/0a7f7336f840e772489e to your computer and use it in GitHub Desktop.
Save geckofu/0a7f7336f840e772489e to your computer and use it in GitHub Desktop.
iterator pattern
################# Enumerable Mixin
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
my_portfolio.any? {|account| account.balance > 2000}
my_portfolio.all? {|account| account.balance >= 10}
################# Abusing the Iteratr Pattern (change resistant or not)
array = ['red', 'green', 'blue', 'purple']
array.each do |color|
puts(color)
if color == 'green'
array.delete(color)
end
end
#=> red, green, purple
class ChangeResistantArrayIterator
# make a shallow copy of the array -- copy points to the original contents
def initialize(array)
@array = Array.new(array)
@index = 0
end
end
################# Amphibious IO object
f = File.open('name.txt')
while not f.eof?
puts f.readline
end
f.close
f = File.open('name.txt')
f.each {|line| puts(line)}
f.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment