SeriesJoiner
A gem for joining items in arrays together into grammatically correct series.
SeriesJoiner extends the Array
class with a join_as_series()
method which is similar to the built-in join()
method. However, join_as_series()
allows for custom delimiters and conjunctions.
Installation
Run the following (perhaps as sudo):
gem install series_joiner
Bundler Configuration
Add the following to your Gemfile:
gem 'series_joiner'
Usage
join_as_series() accepts the following options:
:delimiter # inserted between items, except for the final two (default => ', ')
:final_delimiter # inserted between the final two items (if > 2), but before the conjunction (default => '')
:conjunction # inserted between the final two items (default => ' and ')
By default, items are joined as follows:
['a'].join_as_series #=> 'a'
['a', 'b'].join_as_series #=> 'a and b'
['a', 'b', 'c'].join_as_series #=> 'a, b and c'
['a', 'b', 'c', 'd'].join_as_series #=> 'a, b, c and d'
Here are some examples using custom delimiters and/or conjunctions:
['a', 'b', 'c'].join_as_series(:delimiter => '; ') #=> 'a; b and c'
['a', 'b', 'c'].join_as_series(:conjunction => ' or ') #=> 'a, b or c'
['a', 'b', 'c'].join_as_series(:delimiter => '; ', :conjunction => '; or, ') #=> 'a; b; or, c'
The use of the serial comma (i.e. the final comma sometimes used before the conjunction) is much debated in grammar (en.wikipedia.org/wiki/Serial_comma). By default, SeriesJoiner does not use the serial comma. However, the :final_delimiter
option can be set to ','
to include it:
['a', 'b', 'c'].join_as_series(:final_delimiter => ',') #=> 'a, b, and c'
Implementation
This gem is generated with jeweler and uses shoulda for testing. To run tests:
rake test
Notes
This gem may be compared with the Rails ActiveSupport extension to Array to_sentence()
(github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/conversions.rb). Here are a couple differences:
-
to_sentence()
requires ActiveSupport, whilejoin_as_series
has no dependencies; -
to_sentence()
has I18n support baken in; and, -
to_sentence()
implements the serial comma (see definition above) by default, whilejoin_as_series
does not; and, -
to_sentence()
requires two options (:two_words_connector
and:last_word_connector
) to override a conjunction, instead of the one (:conjunction
) required byjoin_as_series
.
License
MIT License. Copyright © 2011 Cerebris Corporation. See LICENSE.txt for further details.