Class: Array
- Inherits:
-
Object
- Object
- Array
- 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
-
#joined(oxford: true, words_connector: ', ', last_word_connector: ', and ', comma_before: false, max: nil, etc: ', etc.') ⇒ String
Join strings into a single line, splitting them with comma and placing “AND” between the last two items.
Instance Method Details
#joined(oxford: true, words_connector: ', ', last_word_connector: ', and ', comma_before: false, max: nil, etc: ', etc.') ⇒ String
Join strings into a single line, splitting them with comma and placing “AND” between the last two items.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/joined.rb', line 35 def joined(oxford: true, words_connector: ', ', last_word_connector: ', and ', comma_before: false, max: nil, etc: ', etc.') return '' if empty? return etc if max&.zero? array = self truncated = false if max && length > max array = self[0...max] truncated = true end if array.length == 1 result = array.first result += etc if truncated return result end if truncated result = array.join(words_connector) else final = (last_word_connector || '').dup final.sub!(/^,/, '') unless oxford && array.length > 2 result = "#{array[0...-1].join(words_connector)}#{final}#{array[-1]}" end result.gsub!(/"([^"]+)"\s*,/, '"\1,"') if comma_before result += etc if truncated result end |