Project

General

Profile

Actions

Feature #16946

open

Add an `intersperse` method

Added by sos4nt (Stefan Schüßler) over 4 years ago. Updated over 2 years ago.

Status:
Open
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"
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0