Project

General

Profile

Feature #10240

`String#to_a`

Added by sawa (Tsuyoshi Sawada) over 5 years ago. Updated 3 months ago.

Status:
Rejected
Priority:
Normal
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(", ")

Updated by matz (Yukihiro Matsumoto) over 5 years ago

I understand your intention, but I think proposed behavior is bit awkward for to_a of String class.
As you know to_a stands for conversion to array, I don't think "" -> [] is natural conversion from strings.

Matz.

Updated by sawa (Tsuyoshi Sawada) over 5 years ago

Matz is right. I was wrong about the idea. In the cases I showed, I should have had nil values instead of empty strings. I will withdraw this proposal.

#3

Updated by sawa (Tsuyoshi Sawada) 3 months ago

  • Description updated (diff)
  • Subject changed from String#to_a to `String#to_a`

Updated by sawa (Tsuyoshi Sawada) 3 months ago

I do not feel this proposal to be natural any more. Please close this issue.

#5

Updated by Eregon (Benoit Daloze) 3 months ago

  • Status changed from Open to Rejected

Also available in: Atom PDF