Sha256: eaa698caeeae44d8ed751be80c5980588c7e184566a55967528c93d7b292a5d2

Contents?: true

Size: 1.5 KB

Versions: 17

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

module Vedeu

  # Converts the array of elements provided into a comma separated
  # sentence with the penultimate and ultimate elements separated with
  # the word 'and'.
  #
  # @api public
  #
  class Sentence

    # @param (see #initialize)
    # @return (see #construct)
    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')
      @elements = elements
      @label    = 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

    protected

    # @!attribute [r] elements
    # @return [Array]
    attr_reader :elements

    # @!attribute [r] label
    # @return [String]
    attr_reader :label

    private

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

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

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

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

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

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

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

  end # Sentence

end # Vedeu

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
vedeu-0.8.32 lib/vedeu/sentence.rb
vedeu-0.8.31 lib/vedeu/sentence.rb
vedeu-0.8.30 lib/vedeu/sentence.rb
vedeu-0.8.29 lib/vedeu/sentence.rb
vedeu-0.8.28 lib/vedeu/sentence.rb
vedeu-0.8.27 lib/vedeu/sentence.rb
vedeu-0.8.26 lib/vedeu/sentence.rb
vedeu-0.8.25 lib/vedeu/sentence.rb
vedeu-0.8.24 lib/vedeu/sentence.rb
vedeu-0.8.23 lib/vedeu/sentence.rb
vedeu-0.8.22 lib/vedeu/sentence.rb
vedeu-0.8.21 lib/vedeu/sentence.rb
vedeu-0.8.20 lib/vedeu/sentence.rb
vedeu-0.8.19 lib/vedeu/sentence.rb
vedeu-0.8.18 lib/vedeu/sentence.rb
vedeu-0.8.17 lib/vedeu/sentence.rb
vedeu-0.8.16 lib/vedeu/sentence.rb