< All Blog

Ruby: Array Brackets Operator Edge Cases

November 14, 2022

In Ruby, there is a [] (brackets) operator to access items in Array.

https://ruby-doc.org/core-3.1.2/Array.html#method-i-5B-5D

a = [:foo, 'bar', 2]
a[0] #=> :foo
a[2] #=> 2

You can pass [start, length] to the brackets operator to get items based on indexes as follows.

a[1,2] #=> ["bar", 2]
a[2,2] #=> [2]

Edge cases

There is an interesting edge case what this method returns when invalid arguments get passed. It returns an empty array OR nil based on the edge cases.

Let's show some examples. In the following cases, brackets operator returns an empty array.

irb(main):007:0> a[3,0]
=> []

In another example, it returns nil instead.

irb(main):008:0> a[3,-1]
=> nil
irb(main):009:0> a[4,0]
=> nil

Why does it return different result in some edge cases? Actually this behaviour is documented as follows:

If start == self.size and length >= 0, returns a new empty Array. If length is negative, returns nil. https://ruby-doc.org/core-3.1.2/Array.html#method-i-5B-5D

This can be an issue if you did not know this specification and write some codes to handle invalid result for either of an empty array or nil.

Recommended Posts

  1. Ruby: Swap Variables in Oneline

    November 15, 2022
    In Ruby, there is a way to swap values of two different variables without using temporary variables. Let's say there are two variables that we'd like to swap. …