Tips. Ruby for Rails: Hash


RoR hash.jpg

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

Take Out The Papers And The Trash

August 17, 2018

How to clean and clear large tables in MySQL

From time to time our data team gets requests for

Read More

Ruby on Rails vs PHP

May 16, 2018

There’s more than one way to build a web application. No matter what type of application you are

Read More

What to Look for When Considering Application Hosting

May 8, 2018

Cloud computing has made hosting business-critical applications easier and less expensive.

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 Here!