Hashes in Ruby Language
Hashes are an essential data structure in the Ruby programming language. They provide a convenient way to store
and retrieve data using a key-value pair system. In this post, we’ll explore the fundamentals of hashes in Ruby, how to create and manipulate them, and provide real-world examples to illustrate their usage.What is a Hash?
In Ruby, a hash is an unordered collection of key-value pairs. Each key is unique within the hash, and the associated value can be of any data type. Hashes are commonly used to represent data in a structured manner, such as configurations, databases, or any scenario where data needs to be accessed quickly using specific identifiers.
Creating a Hash
You can create a hash in Ruby using the curly braces {}
or the Hash.new
method. Here’s an example of both methods:
# Using curly braces
my_hash = { "name" => "John", "age" => 30, "city" => "New York" }
# Using Hash.new
another_hash = Hash.new
another_hash["fruit"] = "apple"
another_hash["color"] = "red"
Accessing Values
To retrieve values from a hash, you can use the associated keys. For example:
name = my_hash["name"] # Retrieves the value associated with the key "name"
Modifying a Hash
You can add, update, or remove key-value pairs in a hash. Here’s how you can do that:
# Adding a new key-value pair
my_hash["job"] = "Engineer"
# Updating an existing value
my_hash["age"] = 31
# Removing a key-value pair
my_hash.delete("city")
Iterating Through a Hash
You can loop through the keys and values of a hash using methods like each
, each_key
, or each_value
. Here’s an example using each
:
my_hash.each do |key, value|
puts "Key: #{key}, Value: #{value}"
end
Real-World Example
Let’s consider a practical example of using a hash to represent a basic contact list:
contacts = {
"John" => "john@example.com",
"Alice" => "alice@example.com",
"Bob" => "bob@example.com"
}
# Accessing a contact's email
email = contacts["Alice"]
puts "Alice's email is #{email}"
In this example, we’ve created a hash contacts
with names as keys and email addresses as values, making it easy to access a contact’s email using their name as a key.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.