如何获得;“字符串式”;Ruby中数组的连接功能

如何获得;“字符串式”;Ruby中数组的连接功能,ruby,Ruby,考虑以下输入: input = [:a, :b, :c] # output = input.join_array(:x) 获得以下输出(在Ruby中)的可读且简洁的方法是什么: 天真的方法: input = [:a, :b, :c] input.flat_map{|elem| [elem, :x]}[0...-1] # => [:a, :x, :b, :x, :c] 不切割最后一个元素: res = input.reduce([]) do |memo, elem| memo &l

考虑以下输入:

input = [:a, :b, :c]
# output = input.join_array(:x)
获得以下输出(在Ruby中)的可读且简洁的方法是什么:

天真的方法:

input = [:a, :b, :c]

input.flat_map{|elem| [elem, :x]}[0...-1] # => [:a, :x, :b, :x, :c]
不切割最后一个元素:

res = input.reduce([]) do |memo, elem|
  memo << :x unless memo.empty?
  memo << elem
end

res # => [:a, :x, :b, :x, :c]
res=input.reduce([])do | memo,elem|
备注一种天真的方法:

input = [:a, :b, :c]

input.flat_map{|elem| [elem, :x]}[0...-1] # => [:a, :x, :b, :x, :c]
不切割最后一个元素:

res = input.reduce([]) do |memo, elem|
  memo << :x unless memo.empty?
  memo << elem
end

res # => [:a, :x, :b, :x, :c]
res=input.reduce([])do | memo,elem|

备注为了好玩,我们可以使用
join
。但不一定可读或简洁

[:a, :b, :c].join('x').chars.map(&:to_sym) # => [:a, :x, :b, :x, :c]

# Or, broken down:
input = [:a, :b, :c]
output = input.join('x')      # => "axbxc"
output = output.chars         # => ["a", "x", "b", "x", "c"]
output = output.map(&:to_sym) # => [:a, :x, :b, :x, :c] 

为了好玩,我们可以使用
加入
。但不一定可读或简洁

[:a, :b, :c].join('x').chars.map(&:to_sym) # => [:a, :x, :b, :x, :c]

# Or, broken down:
input = [:a, :b, :c]
output = input.join('x')      # => "axbxc"
output = output.chars         # => ["a", "x", "b", "x", "c"]
output = output.map(&:to_sym) # => [:a, :x, :b, :x, :c] 
那么:

input = [:a, :b, :c]
p input.zip([:x].cycle).flatten[0..-2] #=> [:a, :x, :b, :x, :c]
那么:

input = [:a, :b, :c]
p input.zip([:x].cycle).flatten[0..-2] #=> [:a, :x, :b, :x, :c]
压扁产品 可以使用在整个阵列中分布:x,然后展平结果。例如:

input = [:a, :b, :c]
input.product([:x]).flatten
#=> [:a, :x, :b, :x, :c, :x]
修剪阵列 假设您期望的结果不仅仅是意外排除最后一个元素的输入错误,您可以使用或其他类似的方法从数组中修剪最后一个元素。一些例子包括:

input.product([:x]).flatten[0...-1]
#=> [:a, :x, :b, :x, :c]

output = input.product([:x]).flatten
output.pop
output
#=> [:a, :x, :b, :x, :c]
压扁产品 可以使用在整个阵列中分布:x,然后展平结果。例如:

input = [:a, :b, :c]
input.product([:x]).flatten
#=> [:a, :x, :b, :x, :c, :x]
修剪阵列 假设您期望的结果不仅仅是意外排除最后一个元素的输入错误,您可以使用或其他类似的方法从数组中修剪最后一个元素。一些例子包括:

input.product([:x]).flatten[0...-1]
#=> [:a, :x, :b, :x, :c]

output = input.product([:x]).flatten
output.pop
output
#=> [:a, :x, :b, :x, :c]
这是怎么回事

input = [:a, :b, :c]
p input.each_with_object(:x).to_a.flatten[0..-2]
# >> [:a, :x, :b, :x, :c]
这是怎么回事

input = [:a, :b, :c]
p input.each_with_object(:x).to_a.flatten[0..-2]
# >> [:a, :x, :b, :x, :c]

抽象名称的可能重复项是“intersperse”,您会发现该名称存在一些问题。谢谢,名称“intersperse”正是我想要的!抽象名称的可能重复项是“intersperse”,您会发现该名称存在一些问题。谢谢,名称“intersperse”正是我想要的!它不结实。将在较长的符号上分解:)它不健壮。将在较长的符号上分解:)我认为
.flat|u map{elem,:x]}[0…-1]
会更具可读性。您不能使用
[0…-1]
,它将包括尾随
:x
。请注意第三个点
,它使范围更大exclusive@BeatRichartz:啊!所以你看,对一些人来说,它只是更让人困惑:)我认为
.flat|map{elem,:x]}[0…-1]
会更易读一些。你不能使用
[0…-1]
,它会包括尾随
:x
。注意第三个点
,它使范围更大exclusive@BeatRichartz:啊!所以你看,对一些人来说,这更让人困惑:)