Consider the following input:
input = [:a, :b, :c]
# output = input.join_array(:x)
What is a readable and concise way to get the following output (in Ruby):
[:a, :x, :b, :x, :c]
A naive approach:
input = [:a, :b, :c]
input.flat_map{|elem| [elem, :x]}[0...-1] # => [:a, :x, :b, :x, :c]
Without cutting last element:
res = input.reduce([]) do |memo, elem|
memo << :x unless memo.empty?
memo << elem
end
res # => [:a, :x, :b, :x, :c]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments