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.

Examples:

Polite usage (include into your own class):

require 'tins/enum_joined'

class MyList
  include Enumerable
  include Tins::EnumJoined

  def each
    %w[foo bar baz].each { |x| yield x }
  end
end

MyList.new.joined  # => "foo, bar, and baz"

Rude usage (mixin into ::Enumerable globally):

require 'tins/xt/enum_joined'

[1, 2, 3].joined       # => "1, 2, and 3"
Set['a', 'b', 'c'].joined  # => "a, b, and c"

Instance Method Summary collapse

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

Examples:

Default connectors

[1, 2].joined        # => "1 and 2"
[1, 2, 3].joined     # => "1, 2, and 3"

Custom connectors

[1, 2, 3].joined(words: ' / ', last_word: ' / ')
# => "1 / 2 / 3"

Parameters:

  • words (String) (defaults to: ', ') —

    Separator between all items except the last two. Default: ', '.

  • two_words (String) (defaults to: ' and ') —

    Separator between the only two items. Default: ' and '.

  • last_word (String) (defaults to: ', and ') —

    Separator before the last item (3+ items only). Default: ', and ' (Oxford comma).

Returns:

  • (String) —

    the joined sentence



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