Project

General

Profile

Actions

Feature #10240

closed

`String#to_a`

Added by sawa (Tsuyoshi Sawada) over 9 years ago. Updated about 4 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:65034]

Description

I often want to exclude the empty strings from an array of strings. A use case is to join an array of strings with ", ", removing the empty ones, as follows:

["Foo", "", "Bar"].reject(&:empty?).join(", ") # => "Foo, Bar"

In a similar situation with arrays of arrays, the empty ones can be excluded by using * and Array#to_a:

[*[1, 2], *[], *[3, 4]] # => [1, 2, 3, 4]

I would like to propose String#to_a defined as follows:

class String
  def to_a; empty? ? [] : [self] end
end

Then we can do:

[*"Foo", *"", *"Bar"].join(", ")
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0