mb14 mb14 - 2 months ago 28
Ruby Question

intersperse function in ruby?

Hi
I'm looking for an equivalent of the haskell instersperse function in Ruby. Basically that add something (like a separator) between each element of a list.

intersperse(nil, [1,2,3]) => [1,nil,2,nil,3,nil,4].


I'm not asking for any code (I can do it , and I'd probably have done it before you read the question). I'm just wondering if a such function already exists on the standard Ruby platform.

update



I'm not asking for any code, and especially ones using flatten, as that doesn't work (flatten does not only flat one level but all).
I gave the example [1,2,3] just as example, but it should work with

[[1,2],[3,4]].interperse("hello") => [[1,2], "hello", [3,4]]


(Please don't send me any code to make that it work , I have it already

class Array
def intersperse(separator)
(inject([]) { |a,v| a+[v,separator] })[0...-1]
end
end


)

Answer

No