How to convert an array into a string with two different separators in two different places in ruby?

advertisements

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?


pos = 2
[array[0...pos], array[pos..-1]].
  map { |e| e.join ':' }.
  join(' and ')
#⇒ "1:2 and 3:4"