Skip to content

Instantly share code, notes, and snippets.

@connor
Created June 23, 2011 04:29
Show Gist options
  • Save connor/1041904 to your computer and use it in GitHub Desktop.
Save connor/1041904 to your computer and use it in GitHub Desktop.
Ruby array example
array = [ :zero, :one, :two, :three, :four ]
print array.length # 5
print :four == array[4] # true — zero-indexed, so array[4] is the 5th item.
print array[5].nil? # true
print array[6].nil? #true
print [] # nil
print array[5, 0] # nil
print [] == array[5, 0] # true b/c both are nil
print nil # nil
print array[6, 0] # nil
print bil == array[5, 0] # true b/c both are nil
@connor
Copy link
Author

connor commented Jun 23, 2011

Ahh - there's the curvebal.

print [] == nil # returns false.

@markjaquith
Copy link

Yep. array[6,0] does not equal array[5,0]

The only thing I can think is that there's something special about the first out-of-range element (which 5 is). Like the 0 length somehow brings it back in range, or something.

@connor
Copy link
Author

connor commented Jun 23, 2011

In an irb session, here's what I just got:
ruby-1.8.7-p334 :004 > print array[5, 0] => nil # the return value (left) is just empty, not nil ruby-1.8.7-p334 :005 > print array[6, 0] nil => nil #the return value IS nil, not empty.

Hmm. That's interesting. I'll look into it and let you know.

@markjaquith
Copy link

Answer: http://stackoverflow.com/questions/3219229/why-does-array-slice-behave-differently-for-length-n

Consider array = [0,1,2,3]

When you specify array[4,0], you're putting the pointer where the asterisk is here: [0,1,2,3*] and then you're counting for zero length. You're still within the array. But array[4] would be nil because that is equivalent to starting at the asterisk and then going one forward, which busts you out of the array.

@connor
Copy link
Author

connor commented Jun 23, 2011

Ah, that makes sense. Thanks for pointing that out! Sorry I wasn't more of a concrete answer, but I'm glad you found it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment