← Back to Ruby Course | Chapter 5: Hashes | Lesson 6 of 7

Symbol Keys

In this page:

  1. Symbol Keys

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

markup
options = { color: "red", size: "large" }
same_thing = { :color => "red", :size => "large" }

puts options == same_thing
puts options[:color]
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.