0
0
Rubyprogramming~5 mins

Hash creation with symbols and strings in Ruby

Choose your learning style9 modes available
Introduction

Hashes store pairs of keys and values. Using symbols or strings as keys helps organize data clearly.

When you want to group related information like a person's name and age.
When you need to look up values quickly using a key.
When you want to store settings or options with named keys.
When you want to use readable keys that describe the data.
When you want to mix symbols and strings as keys for flexibility.
Syntax
Ruby
hash = { :symbol_key => "value", "string_key" => "value" }

# Or using newer syntax for symbols:
hash = { symbol_key: "value", "string_key" => "value" }

Symbols start with a colon (:), like :name.

Strings are enclosed in quotes, like "name".

Examples
Hash with symbol keys using the older hash rocket syntax.
Ruby
person = { :name => "Alice", :age => 30 }
Hash with symbol keys using the newer, cleaner syntax.
Ruby
person = { name: "Bob", age: 25 }
Hash with string keys using the hash rocket syntax.
Ruby
settings = { "theme" => "dark", "font_size" => 12 }
Hash mixing symbol and string keys.
Ruby
mixed = { name: "Carol", "location" => "NY" }
Sample Program

This program creates a hash with a symbol key and a string key, then prints their values.

Ruby
person = { name: "Dave", "city" => "Boston" }

puts "Name: #{person[:name]}"
puts "City: #{person["city"]}"
OutputSuccess
Important Notes

Symbols are more memory-efficient than strings when used as keys repeatedly.

Access symbol keys with hash[:key] and string keys with hash["key"].

Be consistent with key types to avoid confusion.

Summary

Hashes store key-value pairs using symbols or strings as keys.

Symbols start with a colon and are often preferred for keys.

You can mix symbols and strings but be careful when accessing values.