Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Nice pickup it does look like a Ruby 1.8 vs 1.9 thing. It looks like in 1.9 the String <code>[]=</code> is treated in a similar way as the String <code>insert</code> method.</p> <p>You can use the insert method to insert a string <strong>before</strong> a particular character in another string. So let's take our string "hello" as an example:</p> <pre><code>ruby-1.9.2-p180 :238 &gt; s = "hello" =&gt; "hello" ruby-1.9.2-p180 :239 &gt; s.length =&gt; 5 ruby-1.9.2-p180 :240 &gt; s.insert(s.length, " world") =&gt; "hello world" </code></pre> <p>But now lets try to use insert to insert into <code>s.length + 1</code>:</p> <pre><code>ruby-1.9.2-p180 :242 &gt; s = "hello" =&gt; "hello" ruby-1.9.2-p180 :243 &gt; s.insert(s.length + 1, " world") IndexError: index 6 out of string from (irb):243:in `insert' </code></pre> <p>We get the same behaviour if we use the <code>[]=</code> method:</p> <pre><code>ruby-1.9.2-p180 :244 &gt; s = "hello" =&gt; "hello" ruby-1.9.2-p180 :245 &gt; s[s.length] = " world" =&gt; " world" ruby-1.9.2-p180 :246 &gt; s =&gt; "hello world" ruby-1.9.2-p180 :247 &gt; s = "hello" =&gt; "hello" ruby-1.9.2-p180 :248 &gt; s[s.length + 1] = " world" IndexError: index 6 out of string from (irb):248:in `[]=' </code></pre> <p>So, Ruby 1.9 is clever enough to recognise when you're trying to assign to an index that is just past the end of the string and automagically treats that as an insertion/concatenation. Whether or not this behaviour is desirable probably depends on personal preference, it is certainly good to be aware that it is the behaviour you can expect.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload