如何在Ruby中将数组转换为带有两个不同分隔符的字符串?

3
我希望将一个数组转换为一个字符串,其中在两个不同的位置使用两个不同的分隔符。意思是:
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"

我该如何构建动态和简短的代码,使我能够将一个长度任意的数组转换为字符串,并允许我在不同的位置插入多个分隔符。

我的当前解决方案很混乱和丑陋: 我使用了 #join 并只提供了单个参数。

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

有人能帮我找到更好、更短、更抽象的方法来完成这件事吗?

4个回答

6

你可以使用 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"

4
如果您正在使用rails/activesupport,那么它已经内置了to_sentence方法:
[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"

如果您不知道如何实现,可以参考activesupport的实现方式:)

注意:这并不允许您在序列中间放置"and"。但它非常适用于牛津逗号。


这样做要容易得多,但很遗憾 Ruby 中没有类似的东西。确实非常适合牛津逗号。非常感谢,我将来在使用 Rails 时一定会记住这个方法。 - Zeeshan Shafqat

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

0

代码

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

示例

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"

在哪里

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)"

在哪里

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接