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

Hash Creation

A hash stores pairs of a key and its value, like a dictionary where each word has a meaning. You use curly braces to make one.

In this page:

  1. Hash Creation
Syntax
ruby
hash = { key1 => value1, key2 => value2 }
hash = Hash.new

Hash Creation

A Ruby hash stores key-value pairs, created with curly braces, { key => value } or the modern symbol-key shorthand { key: value }.

Hashes are Ruby's dictionary/map type, letting you look up values by an arbitrary key rather than a numeric index. Keys are usually symbols or strings, though any object can serve as a key.

Note: The { key: value } shorthand is only valid when keys are symbols -- string keys still need the => (rocket) syntax.

Example: Hash Creation

markup
person = { name: "Alice", age: 30 }
old_style = { "name" => "Bob", "age" => 25 }

puts person.inspect
puts old_style.inspect
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
  1. Writing { name => "Alice" } with a bare word, which looks for a variable name; use name: or :name =>.
  2. Mixing string and symbol keys for the same idea, so lookups return nil.
  3. Using a JSON-style { "name": "Alice" } and expecting a string key, when Ruby turns it into the symbol :name.
🔒

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.