Project

General

Profile

Feature #16946

Add an `intersperse` method

Added by sos4nt (Stefan Schüßler) 6 months ago. Updated 6 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:98705]

Description

Haskell has an intersperse function which adds a separator between elements of a list.

It would be pretty useful to have such method(s) in Ruby, too.

Examples for Array and String:

[1, 2, 3].intersperse(0)
#=> [1, 0, 2, 0, 3]

'Hello'.intersperse('-')
#=> "H-e-l-l-o"

I'm aware that I can achieve the above with built-in methods, but it's quite cumbersome: (requiring regular expressions / intermediate arrays)

[1, 2, 3].flat_map { |i| [i, 0] }[0...-1]
#=> [1, 0, 2, 0, 3]

'Hello'.gsub(/(?<=.)./, '-\0')
#=> "H-e-l-l-o"

'Hello'.chars.join('-')
#=> "H-e-l-l-o"

Also available in: Atom PDF