Module: Tins::EnumJoined
- Defined in:
- lib/tins/enum_joined.rb
Overview
Adds joined to any Enumerable, providing human-friendly
sentence-style joining with configurable connectors, similar
to Rails' Array#to_sentence.
Instance Method Summary collapse
-
#joined(words: ', ', two_words: ' and ', last_word: ', and ') ⇒ String
Join all elements into a human-readable sentence.
Instance Method Details
#joined(words: ', ', two_words: ' and ', last_word: ', and ') ⇒ String
Join all elements into a human-readable sentence.
Uses three connectors, mirroring Rails' Array#to_sentence:
| elements | connectors used |
|---|---|
| 0 | (none) — returns "" |
| 1 | (none) — returns the element |
| 2 | two_words |
| 3+ | words + last_word |
56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/tins/enum_joined.rb', line 56 def joined(words: ', ', two_words: ' and ', last_word: ', and ') items = map(&:to_s) case items.size when 0 then '' when 1 then items.first when 2 then items.first + two_words + items.last else head, tail = items[0..-2], items.last head.join(words) + last_word + tail end end |