String Iterator

Jan 14
2008
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

Comments are closed.

Calendar

January 2008
M T W T F S S
« Dec   Feb »
 123456
78910111213
14151617181920
21222324252627
28293031  

Tags