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
# => 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]
# => [2, 3, 4, 5]
# => [1, 2, 3, 4, 5]


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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.