Class: Strings::Inflection::CombinedNoun

Inherits:
Object
  • Object
show all
Defined in:
lib/strings/inflection/combined_noun.rb

Constant Summary collapse

WHITESPACE_REGEX =
/(\s)\s+/.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(words = []) ⇒ CombinedNoun

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Create a combined noun



13
14
15
# File 'lib/strings/inflection/combined_noun.rb', line 13

def initialize(words = [])
  @words = words
end

Instance Attribute Details

#wordsObject (readonly)

Returns the value of attribute words.



8
9
10
# File 'lib/strings/inflection/combined_noun.rb', line 8

def words
  @words
end

Instance Method Details

#+(word) ⇒ Object

Combined with another noun

Parameters:

  • word (String)

    the word to combine with



23
24
25
# File 'lib/strings/inflection/combined_noun.rb', line 23

def +(word)
  CombinedNoun.new(@words + [word])
end

#join_words(separator: ", ", conjunctive: "and", final_separator: nil) ⇒ String

Join a list of words into a single sentence

Examples:

CombinedNoun(["one", "two", "three"]).join_words
# => "one, two and three"

Parameters:

  • words (Array[String])

    the words to join

  • separator (String) (defaults to: ", ")

    the character to use to join words, defaults to ‘,`

  • final_separator (String) (defaults to: nil)

    the separator used before joining the last word

  • conjunctive (String) (defaults to: "and")

    the word used for combining the last word with the rest

Returns:

  • (String)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/strings/inflection/combined_noun.rb', line 45

def join_words(separator: ", ", conjunctive: "and", final_separator: nil)
  oxford_comma = final_separator || separator

  case words.length
  when 0
    ""
  when 1, 2
    words.join(" #{conjunctive} ").gsub(WHITESPACE_REGEX, "\\1")
  else
    ((words[0...-1]).join(separator.to_s) +
    "#{oxford_comma} #{conjunctive} " + words[-1])
      .gsub(WHITESPACE_REGEX, "\\1").gsub(/\s*(,)/, "\\1")
  end
end

#to_aryArray[String]

The combined words

Returns:

  • (Array[String])


65
66
67
# File 'lib/strings/inflection/combined_noun.rb', line 65

def to_ary
  @words.to_ary
end