String Iterator
Jan 14
2008
2008
Comments Off
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