Project

General

Profile

Feature #10240

String#to_a

Added by sawa (Tsuyoshi Sawada) about 5 years ago. Updated about 5 years ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:65034]

Description

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.

History

Updated by sawa (Tsuyoshi Sawada) about 5 years ago

Sorry, there was a mistake in the request. I meant:

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

Updated by matz (Yukihiro Matsumoto) about 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) about 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.

Also available in: Atom PDF