Project

General

Profile

Feature #10240

Updated by sawa (Tsuyoshi Sawada) 9 months ago

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 exclude the empty strings from create an array of strings. A use case them excluding the empty ones. One such situation is when I want to join an array of `join` the strings with `", "`, removing the "` but remove empty ones, as follows: strings before applying `join`. 

 ```ruby 
 ["Foo", "", "Bar"].reject(&:empty?).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] # => "Foo, Bar" 
 ``` 

 In a similar situation with arrays Any of arrays, the empty `array`, `hash` will be removed, and the remaining elements will be expanded 

 Here, the empty ones can will be excluded removed by using `*` the implicit application of `to_a` and `Array#to_a`: the splat operator. 

 ```ruby 
 [*[1, 2], *[], *[3, 4]] # => [1, 2, 3, 4] 
 ``` This will not work with strings though as in the following. 

     [*string1, *string2, *string3] 

 I would like In order to propose 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 as follows: 

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

 Then above, then we can easily do: 

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

 ```ruby 
 [*"Foo", *"", *"Bar"].join(", ") 
 ``` 
 and have the empty strings removed before `join`.

Back