Hashes
Published Jul 27, 2021Updated Sep 9, 2021
Contribute to Docs
A collection of key-value pairs enclosed within curly braces. Values are assigned to keys using the =>
syntax.
Creating Hash with new
Class Method
This will create an empty hash with no default values. Default values may also be provided.
# Create a new empty hashempty_hash = Hash.newputs empty_hash.inspect# Output: {}puts "#{empty_hash[1]}"# An empty hash will have nothing to display# Create a new hash with a default valuehash_default = Hash.new("Codecademy")puts hash_default.inspect# Output: {}# An empty hash will return the default valueputs "#{hash_default[4]}"# Output: Codecademy
Creating Hash Literals
A hash literal is created by enclosing a list of key-value pairs between curly braces.
programming_languages = {"key1" => "Ruby", "key2" => "Python", "key3" => "Java", "key4" => "C++", "key5" => "C#"}puts programming_languages.inspect# Output: {"key1"=>"Ruby", "key2"=>"Python", "key3"=>"Java", "key4"=>"C++", "key5"=>"C#"}
Retrieving a hash value involves putting the required key between square brackets ([]
).
programming_languages = {"key1" => "Ruby", "key2" => "Python", "key3" => "Java", "key4" => "C++", "key5" => "C#"}puts programming_languages["key1"]# Output: Ruby
Changing a hash value involves putting the required key between square brackets ([]
) and assigning a new value.
programming_languages = {"key1" => "Ruby", "key2" => "Python", "key3" => "Java", "key4" => "C++", "key5" => "C#"}# print original value of "key1"puts programming_languages["key1"]# Output: Ruby# change value of "key1"programming_languages["key1"] = "Ruby on Rails"puts programming_languages["key1"]# Output: Ruby on Rails
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Ruby on Codecademy
- Free course
Learn Ruby
Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.Beginner Friendly9 hours - Course
Learn Ruby on Rails
Learn the basics of building applications with this convenient and powerful web development framework.With CertificateIntermediate6 hours