String Iterator
Posted by root Mon, 14 Jan 2008 22:08:00 GMT
class String
class Iterator < String
def initialize(str='', next_char=0)
@next_char = next_char
super(str)
end
def next
return nil if @next_char > self.size
@next_char += 1
get_char(-1)
end
def prev
return nil if @next_char <= 0
@next_char -= 1 if @next_char > 0
get_char()
end
private
def get_char(pos=0)
if block_given?
yield split(//)[@next_char+(pos)]
else
split(//)[@next_char+(pos)]
end
end
end
end
s = String::Iterator.new "abcdef"
while char = s.next
puts char
end
while char = s.prev
puts char
end