If you’ve ever played with Ruby Koans, you may have stumbled upon this puzzling behavior:

ruby
array = [:peanut, :butter, :and, :jelly]

array[4, 0] # => []
array[4, 100] # => []
array[5, 0] # => nil

At first glance, this might seem inconsistent. Why do some of these return an empty array, and one returns nil?

Let’s break it down.

The Basics of Ruby Slicing

Ruby’s Array#[] method accepts two arguments: start_index and length.

ruby
CopyEdit

array[start, length]

  • If start is within bounds (i.e., 0 <= start <= array.size), Ruby returns a sub-array—even if length is 0.
  • If start is outside the bounds (i.e., start > array.size), Ruby returns nil.

Let’s Translate That

Here’s what happens in our example:

ruby
CopyEdit

array = [:peanut, :butter, :and, :jelly]
# Indexes: 0 1 2 3
# Length: 4

array[4, 0]

  • The index 4 is exactly at the end of the array (array.length == 4).
  • Ruby sees this as a valid “empty” slice at the end, so it returns an empty array: [].

array[4, 100]

  • Again, index 4 is valid.
  • Ruby tries to take 100 elements from index 4, but since it’s at the end, there’s nothing to return.
  • Still valid, just empty → [].

array[5, 0]

  • Index 5 is beyond the end.
  • Ruby returns nil because that index doesn’t exist at all.

Need Help With Ruby On Rails Development?

Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.

Hire Ruby on Rails Developer

Support On Demand!

Related Q&A