Sha256: 615a9275ab5bddcccfce2dc2e223923dea0502ff18da77d387a51e38dabda2ec

Contents?: true

Size: 2 KB

Versions: 4

Compression:

Stored size: 2 KB

Contents

# encoding: utf-8

module Corrector

  # Breaks source string to words.
  class Words < Array

    # The source array or string for the current words list.
    #
    # @example:
    #     words = Words.new "М В С2" # => #< Words ["М", "В", "С", "2"]>
    #     words.source # => "М В С2"
    #
    #     words = Wrods.new ["М", "В", "С2"] # => #< Words ["М", "В", "С2"]>
    #     words.source # => ["М", "В", "С2"]
    #
    # Returns either array or string.
    attr_reader :source

    # Initializes the array containing words from the source array or string.
    #
    # @example
    #     Words.new                  # => #<Words []>
    #     Words.new "М В С2"         # => #<Words ["М", "В", "С", "2"]>
    #     Words.new ["М", "В", "С2"] # => #<Words ["М", "В", "С2"]>
    #
    # Params:
    # +value+:: An array of words or a string to be splitted to words.
    #           Default value: <tt>[]</tt>.
    #
    # Returns the array of recognized words from the initial string.
    # Both the +map+ and +to_s+ methods of the array are redefined.
    def initialize(value = [])
      @source = value
      value.is_a?(Array) ? super(value) : super(words)
    end

    # Maps +Words+ class object.
    #
    # @example
    #     words =     Words.new(%w(РАЗ ДВА)).map { |i| i }
    #     words.is_a? Words # => true
    #
    # Returns the mapped +Words+ object.
    def map
      Words.new super.flatten
    end

    # Converts words list to a string. Joins words divided by the +^+ symbol
    # and removes spaces around the slash.
    #
    # @example
    #     words = Words.new %w(К ^ М / C ^ 2)
    #     words.to_s # => "КМ/С2"
    #
    # Returns a converted string with +source+ method to check the source.
    def to_s
      map(&:strip).join(" ").gsub(/\s*\^\s*/, "").gsub(/\s*\/\s*/, "/")
    end

    private

    def line
      @line ||= source.to_s.gsub(/\,/, ".").gsub(/\|/, "/")
    end

    def words
      line.scan(/[А-ЯA-Z]+|\d+\.\d+|\d+|№|\/|%|\$|\^/)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
corrector-0.1.0 app/services/corrector/words.rb
corrector-0.0.3 app/services/corrector/words.rb
corrector-0.0.2 app/services/corrector/words.rb
corrector-0.0.1 app/services/corrector/words.rb