Quantcast
Viewing latest article 8
Browse Latest Browse All 48

Ruby hashes & symbols

Some notes from Michael Hartl’s excellent Rails tutorial on the differences between Hashes, Symbols, and others stuff.

https://www.railstutorial.org/book/_single-page#sec-other_data_structures

Hashes

Hashes are arrays that aren’t limit to integer indexes. Their indexes, or keys, can be almost any object. For example can use strings as keys.

user = {}                          # {} is an empty hash.
user["first_name"] = "Michael"     # Key "first_name", value "Michael"

Instead of defining hashes one item at a time using square brackets, it’s easy to use a literal representation with keys and values separated by =>, called a “hashrocket”:

user = { "first_name" => "foo", "last_name" => "bar" } # hash from hash rocket

Symbols

While strings are fine as hash keys, in Rails symbols are much more popular. Symbols look like strings but are prefixed with a colon. For example :name is a symbol. Think of symbols as strings without all the baggage (faster all at once comparison).

user = { :name => "foo", :email => "bar" } # hash from symbol & hash rocket

Since symbols are so popular, Ruby no supports a new syntax for this special case:

user = { name: "foo", email: "bar" } # hash made from symbols

Note it can get confusing:

{ :name => "foo" }
{ name: "bar" }

:name is a valid symbol but name: has no meaning by itself (only has meaning inside a hash).


Filed under: rails Tagged: hash, rails, ruby, symbol Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 8
Browse Latest Browse All 48

Trending Articles