我想将数组转换为在两个不同位置具有两个不同分隔符的字符串。意思是:
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
有人可以帮我建立一个更好,更短,更抽象的方法吗?
答案 0 :(得分: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"
答案 1 :(得分:4)
如果您使用的是rails / activesupport,那么it's 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"
如果不这样做,请复制activesupport的实现,例如:)
注意:这不允许您将“和”放在序列的中间。不过,它非常适合牛津逗号。
答案 2 :(得分:3)
pos = 2
[array[0...pos], array[pos..-1]].
map { |e| e.join ':' }.
join(' and ')
#⇒ "1:2 and 3:4"
答案 3 :(得分: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 ", ":"]