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.
Ruby’s Array#[] method accepts two arguments: start_index and length.
ruby
CopyEdit
array[start, length]
Here’s what happens in our example:
ruby
CopyEdit
array = [:peanut, :butter, :and, :jelly]
# Indexes: 0 1 2 3
# Length: 4
array[4, 0]
array[4, 100]
array[5, 0]
Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.
Hire Ruby on Rails Developer