Issue #10240 has been reported by Tsuyoshi Sawada.

----------------------------------------
Feature #10240: String#to_a
https://bugs.ruby-lang.org/issues/10240

* Author: Tsuyoshi Sawada
* Status: Open
* Priority: Normal
* Assignee: 
* Category: 
* Target version: 
----------------------------------------
I would like to propose `String#to_a` that is equivalent to the following:

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

The use case/motivation is as follows.

I often have some strings and want to create an array of them excluding the empty ones. One such situation is when I want to `join` the strings with `", "` but remove empty strings before applying `join`.

One way is to explicitly do this:

    [string1, string2, string3].reject(&:empty?).join(", ")

But I prefer an easier way. What comes to my mind is that empty objects that have the `to_a` method can be easily excluded from an array by just using the splat operator:

    [*array, *hash] # => Any of the empty `array`, `hash` will be removed, and the remaining elements will be expanded

Here, the empty ones will be removed by the implicit application of `to_a` and the splat operator.

This will not work with strings though as in the following.

    [*string1, *string2, *string3]

In order to make it work, we may make use of the Rails' `Object#presence`:

    [*string1.presence, *string2.presence, *string3.presence]

but that is too much to type. If we had `String#to_a` as defined above, then we can easily do:

    [*string1, *string2, *string3].join(", ")

and have the empty strings removed before `join`.



-- 
https://bugs.ruby-lang.org/