Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/joined.rb

Overview

Joins elements of array.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2025 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Instance Method Details

#joined(oxford: true, words_connector: ', ', last_word_connector: ', and ', comma_before: false) ⇒ String

Join strings into a single line, splitting them with comma and placing “AND” between the last two items.

Parameters:

  • words_connector (String) (defaults to: ', ')

    The string used to join all but the last element of the list

  • last_word_connector (String) (defaults to: ', and ')

    The string used to join the last element of the list.

  • oxford (Boolean) (defaults to: true)

    Should we place a comma before the :last_word_connector? If false, it will remove a leading comma from the :last_word_connector. If true, it will preserve the leading comma specified in the :last_word_connector, but it will not insert one if not already present.

  • comma_before (Boolean) (defaults to: false)

    Should we move comma before the quotes symbol If false, adds the comma outside quotation marks If true, adds the comma inside quotation marks

Returns:

  • (String)

    The text generated (with items joined)



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/joined.rb', line 30

def joined(oxford: true, words_connector: ', ', last_word_connector: ', and ', comma_before: false)
  return '' if empty?
  return first if length == 1

  final_connector = (last_word_connector || '').dup
  final_connector.sub!(/^,/, '') unless oxford && length > 2

  result = "#{self[0...-1].join(words_connector)}#{final_connector}#{self[-1]}"
  result.gsub!(/"([^"]+)"\s*,/, '"\1,"') if comma_before

  result
end