That's a tricky question!

When we chatted on IRC, I wrote that str[n] = "x" should be equivalent
to str[n, 1] = "x", but after some thought that's doesn't have to be
the case. It might be more "clean" in some way if it was, but the joy
of using Ruby is partly because it's expressive, even if it's not as
clean as Lisp, say.

We already have that str[n] is not the same as str[n, 1] when n ==
length. So the assignment version can also behave differently.

Also, looking at what array does is not helpful, since [][1000] = :x
is meaningful but ""[1000] = "x" isn't.

My feeling (now :-) is that str[str.size] = "x" should raise an error
(like in earlier Ruby) but that str[str.size, n] = "x" should work,
for n = 0, 1 or 1000, in the same way that str[str.size] == nil and
str[str.size, 1] == "".

On Thu, Jun 4, 2009 at 2:23 PM, brian ford <brixen / gmail.com> wrote:
> Hi,
>
> String[]= behaves differently on 1.8 and 1.9 when given a single
> Fixnum argument == to the size of the string. Given the following
> code:
>
> $ cat string.rb
> s = ""
> p s[0]
>
> s[0,0] = "a"
> p s
>
> s = ""
> s[0] = "a"
> p s
>
> s = "x"
> s[1] = "a"
> p s
>
> these are the results:
>
> $ ruby -vw string.rb
> ruby 1.8.6 (2008-08-11 patchlevel 287) [universal-darwin9.0]
> nil
> "a"
> string.rb:8:in `[]=': index 0 out of string (IndexError)
>  >
> $ ruby1.8 -vw string.rb
> ruby 1.8.8dev (2009-06-04 revision 23638) [i386-darwin9.7.0]
> nil
> "a"
> string.rb:8:in `[]=': index 0 out of string (IndexError)
>  >
> $ ruby1.9 -vw string.rb
> ruby 1.9.2dev (2009-05-28 trunk 23601) [i386-darwin9.7.0]
> nil
> "a"
> "a"
> "xa"
>
>
> Given any string s of N characters, s[N] == nil, so I understand that
> to mean that N is out of the bounds of the string. The RDoc for
> String#[]= states that
>
> The forms that take a +Fixnum+ will raise an +IndexError+ if the value
>      > Regexp+ and +String+ forms will silently ignore the assignment."
>
> The RDoc does not appear to have changed on 1.9.
>
> So, my questions are:
>
> 1. should ""[0] = "a" work on 1.8 the way it does on 1.9?
>  > 2. should ""[0] = "a" raise an IndexError on 1.9?
>
> If the answer to the above is "it should raise an IndexError on 1.9",
> then should ""[0,N] = "a" also raise an IndexError?
>
> If the answer is ""[0] = "a" should work as it does on 1.9, can we
> please update the RDoc to somehow explain that while s[N] is out of
> bounds of the string, you can "replace" that non-existent character
> with an arbitrary length string.
>
> Cheers,
> Brian
>
>