ibylich
ibylich

Reputation: 658

Rails method for concatenate

Is it possible to concatenate Array ['a', 'b', 'c'] to String "a, b and c" ?
But ['a', 'b'] should transform to "a and b".

Upvotes: 3

Views: 184

Answers (3)

Ismael
Ismael

Reputation: 16720

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

Upvotes: 2

pjumble
pjumble

Reputation: 16960

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 the last_word_connector:

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

Upvotes: 7

James Kyburz
James Kyburz

Reputation: 14453

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

Upvotes: 1

Related Questions