1

Possible Duplicate:
Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)

Running this code on my ruby interpreter it ends up with 7..4 outputting nil, and 6..4 outputting nothing

arr = [1, 2, 3, 4, 5, 6]

p arr[7..4]
p arr[6..4]

According to the ruby doc if the initial index is out of range it returns a nil, and in this case both (6 & 7) are out of range of the array, but only the first returns a nil.

Edit for clairification: The output is as follows:

nil 
[]

Why would the first return nil and the second []?

Community
  • 1
  • 1
Paul
  • 2,729
  • 20
  • 26
  • It's not a duplicate. In this question we have `..` instead of `,` and reversed borders. – Nakilon Dec 12 '10 at 23:44
  • 1
    @Nakilon: There's no difference, what matters is the first index. @Paul: You should change `puts` with `p`, to avoid confusion about what's the result of the slicing, and what's the result of `puts` itself. – Mladen Jablanović Dec 13 '10 at 13:44
  • OK, I've reread, really, duplicate. – Nakilon Dec 16 '10 at 19:35

1 Answers1

1

Well, probably the interpreter doesn't understand the range "decreasing", trying

puts arr[3..1] 

also returned nothing, maybe because [3..1] is not a range. []s

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Cloudson
  • 65
  • 5
  • 1
    Thats kind of the problem, on one it returns empty [], the other returns the value nil. They SHOULD both either return nil or return [], not one doing nil and one []. This is on 1.8.7 on osx if it makes a difference. – Paul Dec 13 '10 at 02:40
  • 1
    Slicing an array using an "inverted" range is usual in Ruby: for example: `[1,2,3,4][1..-2]` gives `[2, 3]`. – Mladen Jablanović Dec 13 '10 at 13:49
  • lol , I don't knew. Nice! Thanks @Mladen – Cloudson Dec 13 '10 at 19:59