Ruby Tuesday – Array#first

As we continue looking to see how Ruby’s Array class can be seen as a queue, we take a look at Array#first.

Array#first returns the first element of an Array, or nil if the array is empty.

[1, 2 ,3, 4, 5].first
# => 1
[].first
# => nil
[{:a => 1}, :b, [1, 2, 3]].first
# => {:a=>1}

While this in and of itself is nothing spectacular, what it gets us is a way of having Command/Query Separation1, or CQS for short.

Why care about Command/Query Separation?

First, by using it we can start to take a more functional approach to our design. We can “peek” at the first element of an array, and keep peeking to our hearts content and never worry about modifying the state of the queue.

Second, when it is time to “pop” the next element off the queue, we can have the result of the “pop” command be to return a new queue object that is the result of dropping the first item from the array.

This allows us to empty a queue without modifying the original queue.

my_queue = [1, 2, 3, 4, 5]
# => [1, 2, 3, 4, 5]
my_queue.first #peek
# => 1
my_queue.first #peek again
# => 1
after_pop = my_queue.drop(1)
# => [2, 3, 4, 5]
after_pop
# => [2, 3, 4, 5]
my_queue
# => [1, 2, 3, 4, 5]

–Proctor


1. Command/Query Separation states that a method should either return a value, or modify state, but never do both.