HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMajor

Ruby function to join array with commas and a conjunction

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraywithfunctionjoinrubyandconjunctioncommas

Problem

Should take an array such as ['dog', 'cat', 'bird', 'monkey'] and return 'dog, cat, bird and monkey'.

Looking for a more elegant solution.

def self.english_join(array)
  return nil if array.nil?
  return array[0] if array.length == 1
  return array[0..-2].join(', ') + " and " + array[-1] if array.length > 1
end

Solution

Rails (actually ActiveSupport, part of the Rails framework) offers a very nice Array#to_sentence method.

If you are using Rails or ActiveSupport, you can call

['dog', 'cat', 'bird', 'monkey'].to_sentence
# => "dog, cat, bird, and monkey"


The method is automatically customized according to I18n settings. For example, in Italy you should omit the last comma before the and.

['dog', 'cat', 'bird', 'monkey'].to_sentence
# => "dog, cat, bird e monkey"


If you want something without depending on ActiveSupport, you can start using the method source code.

This is just an example

class Array
  def to_sentence
    default_words_connector     = ", "
    default_two_words_connector = " and "
    default_last_word_connector = ", and "

    case length
      when 0
        ""
      when 1
        self[0].to_s.dup
      when 2
        "#{self[0]}#{options[:two_words_connector]}#{self[1]}"
      else
        "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
    end
  end
end

Code Snippets

['dog', 'cat', 'bird', 'monkey'].to_sentence
# => "dog, cat, bird, and monkey"
['dog', 'cat', 'bird', 'monkey'].to_sentence
# => "dog, cat, bird e monkey"
class Array
  def to_sentence
    default_words_connector     = ", "
    default_two_words_connector = " and "
    default_last_word_connector = ", and "

    case length
      when 0
        ""
      when 1
        self[0].to_s.dup
      when 2
        "#{self[0]}#{options[:two_words_connector]}#{self[1]}"
      else
        "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
    end
  end
end

Context

StackExchange Code Review Q#5863, answer score: 29

Revisions (0)

No revisions yet.