Ruby Tip: Normalizing Hash Keys as Symbols

Written by Ben

Ruby hash keys can be any type of object apart from an integer, but typically they are used in two ways when coding a rails app.

With string keys:

{"a" => "hash"}

Or symbol keys:

{:a => "hash"}

When writing a method that uses a hash of arguments you should handle both styles of hashes. There are a number of reasons for this.

  • You work with other developers who have different coding styles and use either method.
  • More flexibility to fit with other bits of code.
  • Cover more bases and its less likely to break.
  • Generally a good design decision.

The easiest way to handle this situation is to normalize all the keys to symbols and Rails provides the symbolize_keys and symbolize_keys! in ActiveSupport for your coding pleasure.

The symbolize_keys method itself is useful to include in standalone ruby scripts and libraries, also its a good example of how to use Enumerable#inject for more complex stuff.

def symbolize_keys
  inject({}) do |options, (key, value)|
    options[(key.to_sym rescue key) || key] = value
    options
  end
end

A small tip that has come in handy on a few occasions.

LEAVE A COMMENT

COMMENT GUIDELINES

please leave a valid email address, it will not be displayed in your comment.

Required fields are marked *

Inappropriate or off-topic comments will be edited or deleted.

Some XHTML allowed:
<a href="http://..." > <blockquote > <code> <del > <em> <strong>

*
*