Rails method for concatenation

Can Array be Concatenated ['a', 'b', 'c']

to String "a, b and c"

?
But ['a', 'b']

must be converted to "a and b"

.

+3


source to share


3 answers


Rails provides a to_sentence

helper:

> ['a', 'b'].to_sentence
 => "a and b" 
> ['a', 'b', 'c'].to_sentence
 => "a, b, and c" 

      



If you want a, b and c

rather than a, b, and c

, you can change last_word_connector

:

> ['a', 'b', 'c'].to_sentence(last_word_connector: " and ")
 => "a, b and c" 

      

+7


source


a = %w{ a b }
str = a[0..-3].each_with_object("") do |item, res|
 res << "#{item}, "
 res
end
str << "#{a[-2]} and  #{a[-1]}"
p str

      



+2


source


a = ['a', 'b', 'c']
result = a[0...-1].join ', '
result += " and #{a[-1]}" if a.length > 1
result # => a, b and C

a = ['a', 'b']
result = a[0...-1].join ', '
result += " and #{a[-1]}" if a.length > 1
result # => a and b

      

+1


source







All Articles