

Mind blowing Ruby String#split bug? - sm_sohan

Ran into a weird bug because of this:<p>&gt; x = &quot;<i>a</i>&quot;<p>=&gt; &quot;<i>a</i>&quot;<p>&gt; x.split(&#x27;*&#x27;)<p>=&gt; [&quot;&quot;, &quot;a&quot;]<p>Expected =&gt; [&quot;&quot;, &quot;a&quot;, &quot;&quot;] or [&quot;a&quot;]<p>It feels bizarre. Anyone has an explanation for this?
======
petercooper
Assuming by the notation you mean what jordsmi says and you mean:

    
    
        x = "*a*"
    

.. then it's not surprising. It works similarly with anything, not just
asterisks. For example:

    
    
        ",a,".split(",") # => ["", "a"]
    

But I don't consider this behavior odd, and it's been the same behavior all
the way from 1.8.6 (the oldest implementation I have installed to test with)
through 2.2.

Think about what's necessary when splitting up a row of CSV, say (or even some
space limited logs or configs). You want that first 'missing' value to be
represented in the output as it affects the position of later values. However,
you don't need the final missing value represented as it has no significance -
it's merely a trailing null value.

Also remember that Ruby has its heritage in Perl with methods like this, and
Perl behaves similarly:

    
    
        perl -e "print join(':', split('\*', '*a*'));"  # => ":a"

------
jordsmi
For people not being able to recreate this is because he doesn't mean x = "a"
he means x = "yay" with y being asterisks.

So

x = "yay"

x.split("y")

=> ["", "a"]

------
Adkron
This must be an older version of Ruby. I can't reproduce the issue.

~~~
dyeje
I am also unable to reproduce this.

