Ruby - Create and Use a Hash

1. Introduction

Hashes in Ruby are powerful data structures that allow storage of key-value pairs. They are similar to dictionaries in some other languages. Unlike arrays which store items by an ordered index, hashes store items by a key, which can be of any object type. This post will guide you on how to create and use a hash in Ruby.

2. Program Steps

1. Create a new hash with key-value pairs.

2. Add a new key-value pair to the hash.

3. Retrieve a value by its key.

4. Print the hash.

3. Code Program

# Creating a new hash with some key-value pairs
person = {
  "name" => "John Doe",
  "age" => 30,
  "city" => "New York"
# Adding a new key-value pair to the hash
person["occupation"] = "Software Developer"
# Retrieving a value by its key
person_name = person["name"]
# Printing the hash and retrieved value
puts "Complete Hash: #{person}"
puts "Name from the hash: #{person_name}"


Complete Hash: {"name"=>"John Doe", "age"=>30, "city"=>"New York", "occupation"=>"Software Developer"}
Name from the hash: John Doe


1. person = {...}: Here, we create a hash named person with three key-value pairs. The keys are strings and are used to identify the associated values.

2. person["occupation"] = "Software Developer": We add a new key-value pair to the person hash with the key being "occupation" and its associated value being "Software Developer".

3. person_name = person["name"]: The value associated with the key "name" is retrieved from the person hash and stored in the variable person_name.

4. puts "Complete Hash: #{person}" and puts "Name from the hash: #{person_name}": The complete hash and the retrieved name are printed to the console.

Hashes are flexible and can have keys and values of any data type. They provide a convenient way to store and retrieve data based on unique keys.