Hashes in Ruby
Hashes in Ruby

Mastering Hashes in Ruby: Your Guide to Efficient Data Organization

In Ruby Programming, a hash is a collection of key-value pairs, similar to a dictionary in Python or an associative array in other programming languages. Each key in a hash is unique and it maps to a specific value so we call it a collection of key-value pairs. In hash, each value is assigned to a key using a hash rocket =>.

Hashes in Ruby

Let’s see how you can create and work with hashes in Ruby.

Creating Hashes in Ruby

In Ruby, you can create a hash using curly braces {} and specify key-value pairs:

# Creating a hash with initial values
person = {
  "name" => "San",
  "age" => 28,
  "occupation" => "QA Engineer"
}

# Creating an empty hash
empty_hash = {}

You can also use Hash.new constructor to create a hash with a default value

# Creating a hash with a default value
grades = Hash.new(0)  # Default value is 0

Accessing hash values

You can access the values in hash using keys, as follows

puts person["name"]        # Outputs: San
puts person["age"]         # Outputs: 28
puts person["occupation"]  # Outputs: QA Engineer

Modifying hash values

Also, you can modify hash values using keys

person["age"] = 31       # Changing the value of the "age" key
person["occupation"] = "Developer"  # Changing the value of the "occupation" key

Iterating Over Hashes:

You can iterate over the keys and values in a hash using various methods like each, each_key, and each_value:

person.each do |key, value|
  puts "#{key}: #{value}"
end

Symbols as Keys in Ruby Hash

In Ruby, it’s common to use symbols as keys in hashes, especially when the keys are not expected to change:

person = {
  name: "Alice",
  age: 25,
  occupation: "Designer"
}

Conclusion

There are many methods to play with Hashes in Ruby, some of which are keys, values, merge, delete, has_key?, and more. You can refer to the Ruby documentation for a comprehensive list of hash methods: Ruby Hash Documentation

Remember that hashes are unordered collections, which means the order of key-value pairs is not guaranteed to be the same as when they were inserted.

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments