How do I convert an array to a string with two different delimiters at two different places in ruby?

I want to convert an array to a string with 2 different delimiters in 2 different places. which means:

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 a dynamic and short code that allows me to convert an array (of any length) to a string that allows me to insert multiple delimiters and in different positions.

My current solution is messy and disgusting: I used #join with one 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 to establish a better, shorter and more abstract way of doing this?

+3


source to share


4 answers


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

      



+3


source


You can use Enumerable # slice_after .



array.slice_after(1).map { |e| e.join ":" }.join(" and ") #=> "1 and 2:3:4"
array.slice_after(2).map { |e| e.join ":" }.join(" and ") #=> "1:2 and 3:4"
array.slice_after(3).map { |e| e.join ":" }.join(" and ") #=> "1:2:3 and 4"

      

+6


source


If you are using rails / activesupport it is built in :

[1,2,3,4].to_sentence # => "1, 2, 3, and 4"
[1,2].to_sentence # => "1 and 2"
[1,2,3,4].to_sentence(last_word_connector: ' and also ') # => "1, 2, 3 and also 4"

      

If you don't, then go to the activesupport implementation like :)

Note. This prevents you from placing your "and" in the middle of the sequence. Perfect for Oxford commas.

+4


source


code

def convert(arr, special_separators, default_separator, anchors={ :start=>'', :end=>'' })
  seps = (0..arr.size-2).map { |i| special_separators[i] || default_separator }
  [anchors.fetch(:start, ""), *[arr.first, *seps.zip(arr.drop(1)).map(&:join)],
    anchors.fetch(:end, "")].join
end

      

<strong> Examples

arr = [1,2,3,4,5,6,7,8]
default_separator  = ':'

      

# 1

special_separators = { 1=>" and ", 3=>" or " }
convert(arr, special_separators, default_separator)
  #=> "1:2 and 3:4 or 5:6:7:8"

      

Where

seps #=> [":", " and ", ":", " or ", ":", ":", ":"]

      

# 2

special_separators = { 1=>" and ", 3=>") or (", 5=>" and " }    
convert(arr, special_separators, default_separator, { start: "(", end: ")" })
  #=> "(1:2 and 3:4) or (5:6 and 7:8)"

      

Where

seps #=> [":", " and ", ":", ") or (", ":", " and ", ":"]

      

0


source







All Articles