Share This Article
Hashes in Ruby are one of the most common data structures available. A hash works using a key-value format. Hashes in Ruby are considered objects, meaning they have specific methods you can use.
Creating a hash
Hash.new
is a method that creates a new hash object.
hash_1 = Hash.new
Hashes can also be created using the literal syntax:
hash_2 = { "key" => "value" }
or
hash_3 = { key: "value" }
Both of these syntaxes are equivalent.
Accessing a value
You can access the values of a hash using the square brackets syntax:
hash_1["key"] # => "value"
or
hash_2[:key] # => "value"
You can also use the fetch
method to access values.
hash_1.fetch("key") # => "value"
or
hash_2.fetch(:key) # => "value"
Checking the presence of a key
You can check if a hash contains a specific key using the has_key?
method:
hash_1.has_key?("key") # => true
or
hash_2.has_key?(:key) # => true
The key?
method does the same thing as the has_key?
method.
hash_1.key?("key") # => true
or
hash_2.key?(:key) # => true
Returning multiple keys and values
You can get an array of all the keys in a hash using thekeys
method:
hash_1.keys # => ["key"]
You can also get an array of all the values in a hash using the values
method:
hash_1.values # => ["value"]
Adding a new key/value
If you want to add a new key/value pair to a hash, you can use the store
method:
hash_1.store("key_2", "value_2")
or
hash_2.store(:key_2, "value_2")
Deleting a key/value pair
If you want to delete a key/value pair from a hash, you can use the delete
method:
hash_1.delete("key")
or
hash_2.delete(:key)
You can also delete a key/value pair from a hash using the delete_if
method.
delete_if
accepts a block, in which you can specify the condition under which you want a key/value pair to be deleted.
This is an example of how you can use delete_if:
hash_1.delete_if { |k, v| v == "value" }
You can also delete a key/value pair from a hash using the reject
method:
hash_1.reject { |k, v| v == "value" }
Filtering
While select
returns a new hash with the key/value pairs that match the condition in the block, reject
returns a new hash with the key/value pairs that don’t match the state in the block.
For example:
hash_1.select { |k, v| v == "value" } # => { "key" => "value" }
hash_1.reject { |k, v| v == "value" } # => {}
Iterating a hash
You can also iterate over a hash using the each
method:
hash_1.each { |k, v| puts "#{k}: #{v}" }
This will print each key/value pair on a new line.
You can also use the each_key
& each_value
methods:
hash_1.each_key { |k| puts k }
hash_1.each_value { |v| puts v }
Merging hashes
You can also combine hashes using the merge
method:
hash_1.merge(hash_2)
This will return a new hash with the contents of both hashes.
I hope you found this article helpful!
If you want to learn more about hashes, I recommend checking out the official Ruby documentation.