replacing comma with and in a list with ruby

Problem
You have a list, usually after using join(“,”) in an array that consists of different values ie “one, two, three, four”, but you want to replace the last comma with and so it would be “one, two, three and four”.

Solution
Use reverse initially to reverse the string, then use sub to replace the last comma with the word and reversed (dna), and then finally reverse the string again.

string_with_and=string_with_commas.reverse.sub(/,/, ‘ dna ‘).reverse

or, thanks to Akhil's comment, for Arrays in Rails we can use the to_sentence method as in:

string_with_no_commas=array.to_sentence(options = {:last_word_connector => ” and “})

2 thoughts on “replacing comma with and in a list with ruby

  1. Thanks Akhil.
    Didn’t know about this one, so that would be useful.
    Did some searching and it appears to be an Array function.
    I would really want to skip the last comma before the ‘and’, and when doing the search there was a mention about :skip_last_comma.
    Looking at the Rails API though it appears only 3 options exist:
    :words_connector
    :two_words_connector
    :last_word_connector

    It turns out that defaults for the :last_word_connector is “,and” so by using:
    array.to_sentence(options = {:last_word_connector => ” and “})
    I can get the same result.

Leave a Reply