How to get "string-like" join functionality for arrays in Ruby

jnorris

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]
Sergio Tulentsev

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.

edited at
0

Comments

0 comments
Login to comment

Related