... Anyway, per class Array - RDoc Documentation it
says: "Returns nil if the index (or starting index) are out of range".
So given array:
array = [:peanut, :butter, :and, :jelly]
One would expect:
array[4] == nil #=> true
array[5] == nil #=> true
Which works, 4 and 5 are both out of range.
However:
array[4,0] == nil #=> false
array[5,0] == nil #=> true
Huh? In actual fact array[4,0] returns an empty array. This seems in
conflict with the docs.
Can someone more enlightened please explain?
As well as Rob's reply there is this recent thread, which has an explanation
from Matz:
http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/f09c65251c72ab6/9a125107e3186534
extracts:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/368268
... So, to summarize, when indexing a position beyond the length of a
string, ruby returns nil. But when indexing a slice beyond the length
of a string, ruby returns an empty string "" for the first index
beyond and then nil.
I don't like that this passes
assert "foo"[3] != "foo"[3,1] ...
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/368271
"foo"[3,1] is "" since when index is within the string, the sought
length will be rounded to fit in the size. And 3 (which equals to the
length of the string) is considered as touching the end of the string,
so the result length is zero. ... matz.
... Here's a way I've thought about it:
Picture the array with the comma after each element ...
That may - or may not! - explain this behaviour: I've been wondering why the
statements with 1 (but not 2) 'superfluous' commas at the end don't give a
syntax error:
arr = #=>
arr = [ 0 ] #=> [0]
arr = [ 0, ] #=> [0]; superfluous comma is ignored
arr = [ 0, 1, 2 ] #=> [0, 1, 2]
arr = [ 0, 1, 2, ] #=> [0, 1, 2]; superfluous comma is ignored
but these give: syntax error, unexpected ',', expecting ']'
# arr = [ 0, 1, 2, 3, ]
# arr = [ , ]
路路路
On Mon, Sep 13, 2010 at 3:55 AM, Mikel Lindsaar <raasdnil@gmail.com> wrote:
On Mon, Sep 13, 2010 at 4:22 AM, Rob Biedenharn <Rob@agileconsultingllc.com>wrote: