Project

General

Profile

Actions

Feature #15562

open

`String#split` option to suppress the initial empty substring

Added by sawa (Tsuyoshi Sawada) almost 6 years ago. Updated almost 6 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:91256]

Description

String#split returns an empty substring if any at the beginning of the original string, even though it does not return an empty substring at the end of the original string:

"aba".split("a") # => ["", "b"]

This is probably heritage from Perl or AWK, and may have some use cases, but in some (if not most) use cases, this looks asymmetric, and the initial empty string is unnatural and often requires some additional code to remove it. I propose to give an option to String#split to suppress it, perhaps like this (with true being the default):

"aba".split("a", initial_empty_string: false) # => ["b"]
"aba".split("a", initial_empty_string: true) # => ["", "b"]
"aba".split("ba", initial_empty_string: true) # => ["b"]

This does not mean to suppress empty strings in the middle. So it should work like this:

"aaaba".split("a", initial_empty_string: false) # => ["", "", "b"]
"aaaba".split("a", initial_empty_string: true) # => ["", "", "", "b"]

Or may be we can even go on further to control both the initial and the final ones like (with :initial being the default):

"aba".split("a", terminal_empty_string: :none) # => ["b"]
"aba".split("a", terminal_empty_string: :initial) # => ["", "b"]
"aba".split("a", terminal_empty_string: :final) # => ["b", ""]
"aba".split("a", terminal_empty_string: :both) # => ["", "b", ""]
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0