Home > Back-end >  Rails: automatically add "and" as a view helper
Rails: automatically add "and" as a view helper

Time:12-13

I'm looking for a function like:

collection([1,2,3]) # '1, 2, and 3.'

I think function collection or something similar is defined somewhere in the Rails helpers but I can't find it.

Can anyone shed some light on this?

CodePudding user response:

I think you are looking for to_sentence

https://apidock.com/rails/Array/to_sentence

CodePudding user response:

to_sentence will do most of what you have asked:

[1,2,3].to_sentence # => "1, 2, and 3"

Punctuation needs to be added yourself:

[1,2,3].to_sentence   "." # => "1, 2, and 3."
# OR
"#{[1,2,3].to_sentence}." # => "1, 2, and 3."

If you want your sentence capitalised (doesn't apply in your example) you can use .humanize:

["one", "two", "three"].to_sentence # => "one, two, and three"
["one", "two", "three"].to_sentence.humanize # => "One, two, and three"
  • Related