instance method to_sentence

Ruby on Rails 2.2.3

Since v2.2.3 Last seen in v2.3.18

Available in: v2.2.3 v2.3.18

Signature

to_sentence(options = {})

Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:

  • :connector - The word used to join the last element in arrays with two or more elements (default: “and”)

  • :skip_last_comma - Set to true to return “a, b and c” instead of “a, b, and c”.

Parameters

options opt = {}
Source
# File activesupport/lib/active_support/core_ext/array/conversions.rb, line 10
        def to_sentence(options = {})          
          options.assert_valid_keys(:connector, :skip_last_comma, :locale)
          
          default = I18n.translate(:'support.array.sentence_connector', :locale => options[:locale])
          default_skip_last_comma = I18n.translate(:'support.array.skip_last_comma', :locale => options[:locale])
          options.reverse_merge! :connector => default, :skip_last_comma => default_skip_last_comma
          options[:connector] = "#{options[:connector]} " unless options[:connector].nil? || options[:connector].strip == ''

          case length
            when 0
              ""
            when 1
              self[0].to_s
            when 2
              "#{self[0]} #{options[:connector]}#{self[1]}"
            else
              "#{self[0...-1].join(', ')}#{options[:skip_last_comma] ? '' : ','} #{options[:connector]}#{self[-1]}"
          end
        end

Defined in activesupport/lib/active_support/core_ext/array/conversions.rb line 10 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::CoreExtensions::Array::Conversions

Type at least 2 characters to search.

↑↓ navigate · open · esc close