On 2006-11-22, Just Another Victim of the Ambient Morality <ihatespam / hotmail.com> wrote:
>
> "AliasX Neo" <kamipride102 / gmail.com> wrote in message 
> news:86904d117a12656ca6e35c32fd8bcbe0 / ruby-forum.com...
>> Well, I've spent the last hour or so debugging one of the stupidest
>> errors I have encountered with Ruby.
>>
>> Let's see my code first:
>>
>> [code]def parse(string, starting, ending)
>>        istart = string.index(starting) + starting.length
>>        iend = string.index(ending, istart)
>>        return string.slice(istart, iend - istart)
>>    end[/code]
>>
>> This function is called about 13 times in my entire script. It breaks on
>> the last one with this error:
>>
>> undefined method `+' for nil:NilClass
>
>     Just out of wild curiosity, did you ever figure this thing out?  We're 
> very eager to learn of bugs in Ruby so they may be fixed although it really 
> looks like this was your error.  Surely, it's not outrageous to think that 
> string.index(starting) can return nil.  Was this the case for you?

It's not only not outrageous - if one reads the spec., it's obvious:

----------------------------------------------------------- String#index
     str.index(substring [, offset])   => fixnum or nil
     str.index(fixnum [, offset])      => fixnum or nil
     str.index(regexp [, offset])      => fixnum or nil
------------------------------------------------------------------------
     Returns the index of the first occurrence of the given _substring_,
     character (_fixnum_), or pattern (_regexp_) in _str_. Returns +nil+
     if not found. If the second parameter is present, it specifies the
     position in the string to begin the search.

        "hello".index('e')             #=> 1
        "hello".index('lo')            #=> 3
        "hello".index('a')             #=> nil
        "hello".index(101)             #=> 1
        "hello".index(/[aeiou]/, -3)   #=> 4


--