Sha256: f853a21f03303ea78a67968e92f84b3e0a19ad7b75835ba8d68993306e0ad286

Contents?: true

Size: 1.38 KB

Versions: 3

Compression:

Stored size: 1.38 KB

Contents

module Vedeu

  # Take a collection of words (elements) and form a sentence from them.
  #
  # @example
  #   elements = ['Hydrogen', 'Helium', 'Lithium']
  #   Vedeu::Sentence.construct(elements) # => 'Hydrogen, Helium and Lithium'
  #
  class Sentence

    # @param elements [Array]
    # @param label [String]
    # @return [String]
    def self.construct(elements, label = 'elements')
      new(elements, label).construct
    end

    # @param elements [Array]
    # @param label [String]
    # @return [Vedeu::Sentence]
    def initialize(elements, label)
      @elements, @label = elements, label
    end

    # @return [String]
    def construct
      if one?
        first

      elsif two?
        elements.join(' and ')

      elsif many?
        [but_last, last].join(' and ')

      else
        "No #{label} have been assigned."

      end
    end

    private

    attr_reader :elements, :label

    # @return [Boolean]
    def one?
      count == 1
    end

    # @return [Boolean]
    def two?
      count == 2
    end

    # @return [Boolean]
    def many?
      count > 2
    end

    # @return [String]
    def but_last
      elements[0...-1].join(', ')
    end

    # @return [String]
    def first
      elements.first
    end

    # @return [String]
    def last
      elements[-1]
    end

    # @return [Fixnum]
    def count
      elements.size
    end

  end # Sentence

end # Vedeu

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
vedeu-0.4.5 lib/vedeu/support/sentence.rb
vedeu-0.4.4 lib/vedeu/support/sentence.rb
vedeu-0.4.3 lib/vedeu/support/sentence.rb