Symbol Keys
Symbol keys use names like :name as the labels in a hash, which is the usual Ruby habit. It is like using short, reusable tags as drawer labels.
In this page:
Syntax
hash = { name: value1, other_name: value2 }
hash[:name]
Symbol Keys
Using symbols (:name) as hash keys is the idiomatic Ruby convention, since symbols are immutable and compare faster than strings.
The shorthand { name: "Alice" } syntax is specifically for symbol keys and is equivalent to { :name => "Alice" }. Mixing symbol and string keys in the same hash is legal but usually a sign of inconsistent design.
Note:
{ name: "Alice" } and { :name => "Alice" } are exactly equivalent -- the colon-shorthand is just newer, more concise syntax.Example: Symbol Keys
options = { color: "red", size: "large" }
same_thing = { :color => "red", :size => "large" }
puts options == same_thing
puts options[:color]
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Mixing
"color"and:coloras keys, sooptions["color"]returnsnil. - Writing
{ color => "red" }without a colon, which looks for a variable namedcolor. - Using keys with spaces or dashes in the short form such as
{ first-name: 1 }, which is a syntax error; use"first-name": 1or:"first-name".
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: