×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Hashes in Ruby

By IncludeHelp Last updated : December 01, 2024

Ruby Hash Collection

In Ruby, hashes are the collection of identical keys and their values. They are like dictionaries, which has an element along with its description. You can retrieve any available value with the help of a key associated with it. It is alike arrays, but here, you can use indexes of an object type, instead of only integer types. Hashes can also be termed as dictionaries, maps, and associative arrays.

You will get nil as return statement if you try to access a hash with a key and that key does not exist.

Now, let us see how we create a hash in Ruby?

Creating a hash in Ruby

You can create a hash inside {} (curly braces). => symbol is required to provide values to the key and to provide multiple key/values to the hash, a comma is used.

Syntax

hash_name = {"key1"=> "value", "key2"=> "value", "key3"=> "value"}
#or
hash_name["key"] = "value"
#or
hash_name = {key1:  "value1", key2:  "value2", key3:  "value3"}

Now, let us understand the concept with the help of some examples given below,

Example 1

id = {   
  "AA101" => "Suresh",   
  "AA102" => "Sanjiv",   
  "AA103" => "Dam",   
  "AA104" => "Swati",
  "AA105" => "Kamlesh"
}      

id.each do |key, value|   
puts "#{key} = #{value}"   
end  

Output

AA101 = Suresh
AA102 = Sanjiv
AA103 = Dam
AA104 = Swati
AA105 = Kamlesh

Explanation

In the above code, we have created a hash with our values by putting it inside curly braces. We are then printing the hash with the help of each method. The hash is having the record of students along with their id. This is the advantage of hashes that we don't have only integer indexes.

Example 2

fruit = {"banana"=>"yellow"}
puts "Enter the number of key/value you want to enter"
i = gets.chomp.to_i
while (i!=0)
  puts "Enter key:"
  x = gets.chomp
  puts "Enter value:"
  v = gets.chomp
  fruit.store(x,v)
  i=i-1
end
fruit.each do |key, value|   
puts "#{key}'s color is #{value}" 
end  

Output

Enter the number of key/value you want to enter
4
Enter key:
Apple
Enter value:
Red
Enter key:
Grapes
Enter value:
Green
Enter key:
Mango
Enter value:
Yellow
Enter key:
Kiwiw
Enter value:
Green
banana's color is yellow
Apple's color is Red
Grapes's color is Green
Mango's color is Yellow
Kiwiw's color is Green

Explanation

In the above program, we are trying to create a hash with the help of user input values. We have first declared a hash with our values. Then we have asked the user for the number of values she wants to store in the hash. We are making use of the hash.store method to store the user input keys and their corresponding values. At last, we are printing all the values with the help of .each method.

Hash Methods

This table provides links to detailed examples and explanations of various Ruby Hash methods, along with a brief description of their functionality:

Method Name Description
Ruby Hash.default(key) Returns the default value for the given key.
Ruby Hash.default=obj Sets the default value for the hash.
Ruby Hash.default_proc Gets or sets the default proc for the hash.
Ruby Hash.default_proc=obj Assigns a new default proc to the hash.
Ruby Hash.include? Checks if the given key is present in the hash.
Ruby Hash.assoc Searches the hash for a key-value pair with the specified key.
Ruby Hash.has_value? Checks if the given value exists in the hash.
Ruby Hash.has_key? Returns true if the hash contains the given key.
Ruby Hash.compact Returns a hash with nil values removed.
Ruby Hash.compact! Removes nil values from the hash in place.
Ruby Hash.delete Deletes a key-value pair by key.
Ruby Hash.delete_if Deletes key-value pairs for which the block evaluates to true.
Ruby Hash.dig Extracts the nested value specified by a sequence of keys.
Ruby Hash.each Iterates over each key-value pair in the hash.
Ruby Hash.each_pair Alias for the each method.
Ruby Hash.each_key Iterates over each key in the hash.
Ruby Hash.each_value Iterates over each value in the hash.
Ruby Hash.insert Adds or updates a key-value pair in the hash.
Ruby Hash.eql? Checks if two hashes are equal.
Ruby Hash.fetch Retrieves the value for a given key, raising an error if the key does not exist.
Ruby Hash.fetch_values Fetches values for the specified keys.
Ruby Hash.flatten Returns a flattened array of the hash.
Ruby Hash.invert Returns a new hash with keys and values swapped.
Ruby Hash.keep_if Deletes elements for which the block evaluates to false.
Ruby Hash.key? Checks if the given key is present in the hash.
Ruby Hash.key?(value) Returns the key for the given value, or nil if not found.
Ruby Hash.keys Returns an array of all keys in the hash.
Ruby Hash.merge Combines two hashes into a new hash.
Ruby Hash.merge! Combines two hashes, modifying the original hash.
Ruby Hash.merge {block} Merges two hashes, resolving conflicts using a block.
Ruby Hash.rehash Rebuilds the hash based on its current keys and values.
Ruby Hash.reject Returns a new hash excluding key-value pairs for which the block evaluates to true.
Ruby Hash.reject! Deletes key-value pairs from the hash for which the block evaluates to true.
Ruby Hash.replace Replaces the contents of the hash with the contents of another hash.
Ruby Hash.select Returns a new hash with key-value pairs for which the block evaluates to true.
Ruby Hash.store Stores a key-value pair in the hash.
Ruby Hash.length Returns the number of key-value pairs in the hash.
Ruby Hash.transform_keys Returns a new hash with all keys transformed using the given block.
Ruby Hash.transform_values Returns a new hash with all values transformed using the given block.
Ruby Hash.update Updates the hash with key-value pairs from another hash, overwriting existing keys.
Ruby Hash.values Returns an array of all values in the hash.
Ruby Hash.values_at Returns an array containing the values for the specified keys.
Ruby Hash.rassoc Returns the first key-value pair whose value matches the given object.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.