The Handiest Ruby Hash Methods
Ruby Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.
It is used so much that it would be beneficial to know and even memorize some of the most commonly used methods for hashes. If you want to know more about Ruby hashes, take a look at Ruby-Doc
for this article our hash will be :
languages_creators = { ruby: "Matz", javascript: "Brendan", python: "Guido" }
.keys
The .keys method access the keys of the hash
languages_creators.keys
[:ruby, :javascript, :python]
.values
The .values method access the values of the hash
languages_creators.values
["Matz", "Brendan", "Guido"]
[key]
This method gets the value of a certain key, notice we are using the colon since keys are symbols in our hash
languages_creators[:ruby]
Matz
.length
The .length method returns the count of the pair number in the hash
languages_creators.length
3
.clear
The .clear method removes all key-value pairs from the hash
languages_creators.clear
{}
.delete(key, or value)
The .delete method removes the pair based on the given key or the value.
languages_creators.delete(:python:)
"Guido"
{:ruby=>"Matz", :javascript=>"Brendan"}
.empty?
The .empty? method returns true if the hash has no key-value pairs
languages_creators.empty?
false
.has_key?(key)
The .has_key? method returns true if the hash has the given key
languages_creators.has_key?(:javascript)
true
.has_value?(value)
The .has_key? method returns true if the hash has the given value
languages_creators.has_value?("Matz")
true
.member?(key)
The .member? method returns true if the given key is present in the hash
languages_creators.member?(:ruby)
true
.invert
The .invert method returns a new hash created by using hash values as keys, and the keys as values.
languages_creators.invert
{"Matz"=>:ruby, "Brendan"=>:javascript, "Guido"=>:python}
.to_a
The .to_a method converts a hash into a nested array.
languages_creators.to_a
[[:ruby, "Matz"], [:javascript, "Brendan"], [:python, "Guido"]]
.flatten
The .flatten method returns a new array that is a one-dimensional flattening of the hash.
languages_creators.flatten
[:ruby, "Matz", :javascript, "Brendan", :python, "Guido"]
For More Information
Top comments (1)
.delete(key, or value)
delete method accepts keys
.has_value?(value)
The .has_key? method
typo