Created
June 23, 2011 04:29
-
-
Save connor/1041904 to your computer and use it in GitHub Desktop.
Ruby array example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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.
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
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.