Tips. Ruby for Rails: Hash

Facebook
Twitter
LinkedIn

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.

You might also like:   The Ruby Unbundled Series: Designing and Launching New Features in Rails

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
{{cta(‘5019e5e3-8348-4b05-b8bf-ede6bb67025e’)}}

Want more posts like this?

What you should do now:

Facebook
Twitter
LinkedIn

Easy Application Deployment to AWS

Focus on development, not on managing infrastructure

Deploying, running and managing your Ruby on Rails app is taking away precious resources? Engine Yard takes the operational overhead out of the equation, so you can keep innovating.

  • Fully-managed Ruby DevOps
  • Easy to use, Git Push deployment
  • Auto scaling, boost performance
  • Private, fully-configured Kubernetes cluster
  • Linear pricing that scales, no surprises
  • Decades of Ruby and AWS experience

14 day trial. No credit card required.

Sign Up for Engine Yard

14 day trial. No credit card required.

Book a Demo