Tips. Ruby for Rails: Hash


RoR hash

A hash in Ruby contains keys with corresponding values like {a: 1, b: 2}. Here the keys are :a and :b. The : tells you these are symbols. The hash above uses the new syntax of hash introduced in Ruby 2.0. If you see {:a => 1, :b => 2}, this is the same as the hash above.

In Rails, hash typically appears when passing options. Here's code that gets all the messages that are locked.

Message.where(locked: true)

Standalone hashes should have {} but inside a method, you can omit them. The code above is similar to

Message.where({ locked: true })

The values on a hash can also be hashes and you see this in a lot of places in Rails. For example,

<%= form_with(model: @post, data: { behavior: "autosave" }, html: { name: "go" }) do |form| %>
<% end %>

form_with takes 1 hash as a parameter. In this case, the keys of the hash are model, data, and html. The value of model is the ActiveRecord object @post. The values of data and html are the hashes { behavior: "autosave" } and { name: "go" }, respectively.

Symbols vs Strings

Symbols and strings can both be used as keys on hashes. In Rails, both will return the same results.

Message.where(locked: true)
Message.where("locked" => true)

The second line is the hash syntax prior to Ruby 2.0 and is still valid today. If you want to use strings as your keys you need to use this syntax.

While symbols and strings give you the same results when used as keys in hashes, they are not the same thing. A symbol is immutable while a string is mutable. You can't change a symbol once it's created. :locked on different lines in your code is the same object. The locked on different lines on the other hand are different objects.

Use symbols instead of strings on your hash keys. Most Rails code use symbols.

What do you think? Leave your comments below.

Deploy and run your apps on Engine Yard

Related posts

RubyConf Round Up

November 27, 2018

The City: Los Angeles, California

Read More

It's Almost Time For Ruby Conf 2018!

November 6, 2018

It’s autumn and November is right around the corner! We all know what this means…

Read More

Jekyll and Engine Yard: A Match Made in The Clouds

October 29, 2018

Blogging is without a doubt the most important way to get your ideas out to the world, whether

Read More

Christopher Rigor

Christopher Rigor is a Senior Technical Evangelist at Engine Yard. He’s a long time Rails user, system administrator, and recently became a contributor of RailsInstaller. Previously, he was the DevOps Support Manager for Asia-Pacific at Engine Yard.
Find me on:


Subscribe to our Blog