Ruby hashes are collections of key-value pairs.
They are similar to dictionaries in
other programming languages and allow for efficient data retrieval based on keys
Creating a Hash
You can create a hash using curly braces {} or the Hash.new method:
# Using curly braces
person = { name: "Alice", age: 30, city: "New York" }
# Using Hash.new
empty_hash = Hash.new
Common Hash Methods
Accessing Values
Use the key to access the corresponding value.
puts person[:name] # Output: Alice
Adding/Updating Key-Value Pairs
You can add a new key-value pair or update an existing one.
person[:email] = "alice@example.com" # Add
person[:age] = 31 # Update
Deleting a Key-Value Pair
Use delete to remove a key-value pair.
person.delete(:city) # Removes the :city key
Checking for Keys or Values
Use key? or has_key? to check if a key exists, and value? for values.
puts person.key?(:age) # Output: true
puts person.value?("Alice") # Output: true
Getting Keys or Values
Use keys to get an array of keys, and values to get an array of values.keys =
person.keys # Output: [:name, :age, :email, :country, :occupation]
values = person.values # Output: ["Alice", 31, "alice@example.com", "USA",
"Engineer"]
Iterating Over a Hash
Use each to iterate through the key-value pairs.
person.each do |key, value|
puts "#{key}: #{value}"
end
Example:
person = { name: "Alice", age: 30, city: "New York" }
# Accessing a value
puts person[:name] # Output: Alice
# Adding/updating
person[:email] = "alice@example.com"
person[:age] = 31
# Deleting a key
person.delete(:city)
# Iterating through the hash
person.each do |key, value|
puts "#{key}: #{value}"
end
# Checking keys and values
puts person.key?(:age) # Output: true
puts person.value?("Alice") # Output: true
# Merging with another hash
additional_info = { country: "USA", occupation: "Engineer" }
person.merge!(additional_info)
# Displaying keys and values
puts person.keys # Output: [:name, :age, :email, :country, :occupation]
puts person.values # Output: ["Alice", 31, "alice@example.com", "USA", "Engineer"]