I want to convert an array in to a string with two different separators at two different places. meaning:
array = [1,2,3,4]
after converting: separator 1: (":") separator 2: ("and")
string = "1:2:3: and 4"
OR
string = "1:2 and 3:4"
How can I build dynamic and short code that lets me convert an array (of any length) into a string which allows me to insert more than one separator and at different positions.
My current solution is messy and hideous: I have used #join with a single argument.
def oxford_comma(array)
if array.length == 1
result_at_1 = array.join
return result_at_1
elsif array.length == 2
result_at_2 = array.join(" and ")
return result_at_2
elsif array.length == 3
last = array.pop
result = array.join(", ")
last = ", and " + last
result = result + last
elsif array.length > 3
last = array.pop
result = array.join(", ")
last = ", and " + last
result = result + last
return result
end
end
Can someone please help me establish a better, shorter and more abstract method of doing this?