Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Koans - about_arrays.rb [duplicate]

Tags:

arrays

ruby

I'm working on the about_arrays.rb file within Ruby Koans and I noticed this piece of code and I'm not sure why the answer is what it is:

def test_slicing_arrays
  array = [:peanut, :butter, :and, :jelly]

  assert_equal [], array[4,0]
  assert_equal [], array[4,100]
  assert_equal nil, array[5,0]
end

Based on the output for Ruby Koans, can someone explain to me why array[4,0] would evaluate to [] while array[5,0] evaluates to nil?. Why wouldn't array[5,0] also evaluate to []?

Out of curiosity, I tried array[6,0], array[7,0], and so on and also got nil. Is there something special that Ruby does for the array index next in line to get something appended to it?


EDIT:

I found "Array slicing in Ruby: looking for explanation for illogical behaviour (taken from Rubykoans.com)", which asks the same question, but I'm still not understanding how indices work in array slicing.

like image 636
wmock Avatar asked Sep 02 '26 00:09

wmock


1 Answers

The s[n, 0] defines a place just before or after a character, and often before one and after another.

Source.

The first argument to the slice is the lower bound. When it's 4, it is still part of the array, just pointing to the very end. When the lower bound is beyond the length of the array, it's always nil.

It's best to think of the offsets of the spaces between the element values.

RubyFiddle.

like image 67
alex Avatar answered Sep 03 '26 22:09

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!