A Caution On Literal Symbols

I learned early on in my software engineering career that passing around literal strings in code is a very bad idea especially if that string is being used to control logic. A single misplaced letter in that string and before you know it it’s 3:27am and you’re wondering why the output of your parser is hopelessly incorrect.

A growing trend in the Ruby/Rails community however has been to pass around symbols as method arguments, but because symbols are compared as if they are strings this can dangerous as well. I’ll illustrate this in the following snippet from an IRb session:

 1  >> def foo( bar )
 2  >>   puts "Baz!" if bar == :bar
 3  >> end
 4  => nil
 5  >> foo( :bar )
 6  Baz!
 7  => nil
 8  >> foo( :ber )
 9  => nil
10  >> BAR = :bar
11  => :bar
12  >> foo( BAR )
13  Baz!
14  => nil
15  >> foo( BER )
16  NameError: uninitialized constant BER

In this example on lines 5 and 8 we call the function with a literal symbol except on line 8 it’s misspelled. The result for line 8 is that nothing is output, but with no indication that something is wrong. On line 10 we assign the symbol to a constant and then on lines 12 and 15 we again call the function passing the constant but with a similar mispelling on line 15. This time however a NameError is raised and we are notified that there is something wrong with our code.

It pays to double check your code if you use lots of symbols and consider using constants in places where symbols control important logic. It’s easy to press the wrong key, but can be hard to correct if that mistake is buried deep in your code.

Farrel Lifson is a lead developer at Aimred.

About Aimred

Aimred is a specialist Ruby and Ruby on Rails development house and consultancy based in Cape Town, South Africa.

We provide Ruby and Ruby on Rails development, consulting and training services to businesses and organisations of all sizes. If you want to find out how we can help you, contact us at info@aimred.com.

Recent Posts

Yearly Archives