Sha256: ebf1ce4a76c33b15c3839e49a3080299df736da3bd451b181da8328ebee512b8

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

module ChunkyText
  class Chunker
    
    attr_reader :max_length, :chunk_array, :get_chunk
    attr_accessor :string

    def initialize(string, max_length)
      @string = string
      @max_length = max_length
    end 

    def get_chunk(input_string)
      smaller_string = input_string.slice(0,max_length)

      if last_punctuation_mark(smaller_string)
        smaller_string.slice(0,last_punctuation_mark(smaller_string) + 1)
      else
        smaller_string
      end
    end

    def chunk_array
      input_string = string.clone
      array = []
      while input_string.length > 0 do
        array << get_chunk(input_string)
        
        input_string.slice!(0..max_length)
      end
      input_string = string.clone
      array
    end

    private

    def last_punctuation_mark(string)
      punctuation_mark_positions = []
      ['!','?','.'].each do |p_mark|
        punctuation_mark_positions <<  string.rindex(p_mark)
      end
      punctuation_mark_positions.reject! { |item| item == nil }
      punctuation_mark_positions.max
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ChunkyText-0.0.1 lib/ChunkyText/chunker.rb