Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Staying Out of Trouble

Given the curious relationship between symbols and strings, it probably will come as no surprise that the best way to screw up with a symbol is to use it when you wanted a string, and vice versa. As we have seen, you want to use strings for data, for things that you might want to truncate, turn to uppercase, or concatenate. Use symbols when you simply want an intelligible thing that stands for something in your code.

The other way to go wrong is to forget which you need at any given time. This seems to happen a lot when using symbols as the keys in hashes. For example, take a look at this code fragment:

# Some broken code

person = {}
person[:name] = 'russ'
person[:eyes] = 'misty blue'

# A little later...

puts "Name: #{person['name']} Eyes: #{person['eyes']}"

The code here is broken, but you might have to look at it a couple of times to see that the keys of the person hash are symbols, but the puts statement tries to use strings. What you really want to say here is:

puts "Name: #{person[:name]} Eyes: #{person[:eyes]}"

This kind of mistake is common enough that Rails actually provides a Band-Aid for it in the form of the HashWithIndifferentAccess class. This convenient, but somewhat dubious bit of code is a subclass of Hash that allows you to mix and match strings and symbols with cheerful abandon.

  • + Share This
  • 🔖 Save To Your Account