← Back to Ruby Operators

Shovel Operator

Ruby's Shovel Operator (<<) is used to "shovel" some object into a container. The programming lingo for this type of operation is append. You append an item to the end of an array. Or you append a string to the end of another string (a string is a container of characters). Many Ruby and Rails classes override this operator to do an append-like operation with the object at hand. Let's look at some examples.

Shovel into an Array

The Array#<< docs give us a good starting point for understanding this operator. Here is an example of appending several different types of objects to an array:

> items = [:a, :b]
=> [:a, :b]
> items << :c
=> [:a, :b, :c]
> items << [1,2,3]
=> [:a, :b, :c, [1, 2, 3]]
> items << true
=> [:a, :b, :c, [1, 2, 3], true]

Shovel into a String

A string is essentially a container of characters. Thinking about it in those terms, we can shovel more characters into that container.

> message = "Hello"
=> "Hello"
> message << " World"
=> "Hello World"

The docs take it a step further showing that we can shovel an integer into a string. That integer is treated as a codepoint and converted to the corresponding character.

> message << 33
=> "Hello World!"

Shovel into a File

A fun way that a Ruby class overrides the shovel operator is to append to a file.

> file = File.open("example.txt", "w")
=> #<File:example.txt>
> file << "This is the first "
=> #<File:example.txt>
> file << "line of the file\n\n"
=> #<File:example.txt>
> file << "One\n" << "Two\n" << "Three"
=> #<File:example.txt>
> file.close
=> nil

The contents of the file now look like this:

This is the first line of the file

One
Two
Three

Shovel into an ActiveRecord Association

ActiveRecord overrides << so that we can add a new record to a has_many association.

author = Author.find_by(id)
author.books << Book.new(book_params)