at.
at.

Reputation: 52580

Easy way to separate strings in an array with commas in Rails with and before last string

I have a method to insert commas between strings and have an "and" before the last element:

def commas(array)
  return '' if array.length == 0
  return array.first if array.length == 1
  return "#{array[0..-2].join(', ')} and #{array.last}"
end

Just curious if there's a Rails or Ruby method to easily achieve this?

Upvotes: 2

Views: 985

Answers (1)

mind.blank
mind.blank

Reputation: 4880

Rails has a method to_sentence:

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

Upvotes: 4

Related Questions