From: "Ara.T.Howard" Date: 2004-07-22T07:32:03+09:00 Subject: Re: substring by range parameter (bug?) On Thu, 22 Jul 2004, D T wrote: >> >> 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. >> > > Thanks. I know that. sorry - did not read your post closely enough. > That is why I expect "foobar"[-1..-2] returns nil as "foobar"[-1..-3] did. > But it returns an empty string instead of nil, it seems to me that this is a > bug. hmmmm. does seem strange. > In fact, if start is -n and end is < -(n+1), it will return nil. ( like > -2..-4, -2..-5 ) > The problem is only when start is -n and end is -(n+1), it always return > empty string. (like -2..-3, -3..-4) strange. > How does it possible that a substring is empty string ? well, there is always idx = 0 len = 0 'foobar'[idx, len] > And the tricky part is, it do existe and you can re-assign to it too. like: > s = "foobar"; s[-3..-4] = "xxx"; > So, my question is, is this a bug, or special feature for substring when > range is -n..-(n+1) ? i can only imagine it happen somehow because len = end - start_inclusive + 1 so 0 = (-4 - -3) + 1 and 0 len give back empty string... kind of looks like it from the source: static VALUE rb_str_aref(str, indx) VALUE str; VALUE indx; { long idx; switch (TYPE(indx)) { default: /* check if indx is Range */ { long beg, len; switch (rb_range_beg_len(indx, &beg, &len, RSTRING(str)->len, 0)) { case Qfalse: break; case Qnil: return Qnil; default: return rb_str_substr(str, beg, len); } } idx = NUM2LONG(indx); goto num_index; } return Qnil; /* not reached */ } i've looked at rb_range_beg_len and this looks to be the problem - but how to fix it? should these types of ranges throw an error in the first place? like -1...-1 ?? -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 ===============================================================================