简体   繁体   中英

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?

Rails has a method to_sentence :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM