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