Buffer For Iterating Over N-letter-sequences Or Tuples In A String
Join the DZone community and get the full member experience.Join For Free
class TextBuffer def initialize(text) @text = text @pos = 0 end # checks position: kann man noch einen n-tupel extrahieren? def has_tuple?(tsize=2) @pos <= @text.length-tsize end # gets next tuple and advances position # we want all possible n-tuples, so we advance only 1 step (and not tzize) def get_tuple(tsize=2) tuple = @text[@pos..@pos+tsize-1] @pos += 1 return tuple end def reset_position @pos = 0 end endUse
test "has_tuple, get_tuple gets all tuples" do buffer = TextBuffer.new('abcd') tuples_expected = ['ab', 'bc', 'cd'] tuples_found =  while buffer.has_tuple? do tuples_found << buffer.get_tuple end assert_equal tuples_expected.size, tuples_found.size (0..tuples_expected.size).each do |i| assert_equal tuples_expected[i], tuples_found[i] end endI would prefer to have an each_tuple method but I don't know how to implement it.
Strings Buffer (application) Tuple Data Types
Opinions expressed by DZone contributors are their own.