DEV Community

Joshua Jones
Joshua Jones

Posted on

Hashes and Symbols in Ruby

Image description

Hashes with .each:
Image description

If something doesn't exist in value, you will receive (nil).
If you don't want that you can create a default value. Using hash.new you can specify what it should be.
Image description

Symbols:
There can only be one copy of a symbol at a time
Symbols make good hash keys for a few reasons:

-They’re immutable, meaning they can’t be changed once they’re created;
-Only one copy of any symbol exists at a given time, so they save memory;
-Symbol-as-keys are faster than strings-as-keys
because of the above two reasons.

Image description

Converting Between Symbols and Strings
Image description

You can use (.intern) to switch a string into a symbol
(=>) hash rocket style
Image description

Alternate way than hash rocket for symbols
Image description

When you want to filter a hash for values that meet a certain criteria
Image description

Top comments (0)