substring by range parameter (bug?)

Discussion in 'Ruby' started by D T, Jul 21, 2004.

  1. D T

    D T Guest

    s="0123456789"
    s[-1..-2] #=> ""
    s[-2..-1] #=> "89"
    s[-1..-3] #=> nil
    s[-3..-1] #=> "789"
    s[-1..-2] = "..." ; s #=> "012345678...9"

    Expect s[-1..-2] returns nil as s[-1..-3]. (bug ? it returns empty string
    instead of nil.)

    _________________________________________________________________
    Don’t just search. Find. Check out the new MSN Search!
    http://search.msn.click-url.com/go/onm00200636ave/direct/01/
     
    D T, Jul 21, 2004
    #1
    1. Advertisements

  2. D T

    Ara.T.Howard Guest


    for ranges, start must be <= end and -1 is not <= -2

    eg. for the string "foobar":

    ---- --- ----
    char idx nidx
    ---- --- ----
    f 0 -6
    o 1 -5
    o 2 -4
    b 3 -3
    a 4 -2
    r 5 -1

    ~ > irb
    irb(main):001:0> "foobar"[-2..-1]
    => "ar"
    irb(main):002:0> "foobar"[-6..-4]
    => "foo"
    irb(main):003:0> "foobar"[-3..-1]
    => "bar"

    cheers.

    -a
    --
    ===============================================================================
    | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
    | PHONE :: 303.497.6469
    | A flower falls, even though we love it;
    | and a weed grows, even though we do not love it.
    | --Dogen
    ===============================================================================
     
    Ara.T.Howard, Jul 21, 2004
    #2
    1. Advertisements

  3. Hi, Ara!

    I understand what you mean.
    However, the return values should be consistent even if the range object
    doesn't make sense.
    How would you explain the inconsistency?

    The only explanation I can think of is:

    s[-1..-1] #=>"9"
    s[-1..-2] #=>"", because one step back, one less character...
    s[-1..-3] #=>nil, because there's no "less character" concept beyond empty
    string.

    Sam

    ============================================================================
    ===
     
    Sam Sungshik Kong, Jul 21, 2004
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.