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:
Syntax
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
person = { name: "Alice", age: 30 }
old_style = { "name" => "Bob", "age" => 25 }
puts person.inspect
puts old_style.inspect
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
- Writing
{ name => "Alice" }with a bare word, which looks for a variablename; usename:or:name =>. - Mixing string and symbol keys for the same idea, so lookups return
nil. - 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: