Home » Ruby programming

Hash.select Method with Example in Ruby

Ruby Hash.select Method: Here, we are going to learn about the Hash.select Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on March 14, 2020

Hash.select Method

In this article, we will study about Hash.select Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with the help of its syntax and program code in the rest of the content.

Method description:

This method is a public instance method that is defined in the ruby library especially for the Hash class. This method works in a way that it removes every key-value pair from the hash object for which the block has evaluated to be false. If you are not providing any block, then this method will return an enumerator.

This method is one of the examples of non-destructive methods where changes created by the methods are non-permanent or temporary.

Syntax:

    Hash_object.select
    or
    Hash_object.select{|key,value| block}

Argument(s) required:

This method does not require any argument. You will need to pass a block with the method for its better implementation.

Example 1:

=begin
  Ruby program to demonstrate select method
=end	

hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}

puts "Hash select implementation"

puts "Enter the key you want to keep:"
ky = gets.chomp

puts "Hash after select :#{hash1.select{|key,value| key==ky}}"

puts "Self hash object : #{hash1}"

Output

Hash select implementation
Enter the key you want to keep:
 color
Hash after select :{"color"=>"Black"}
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}

Explanation:

In the above code, you can observe that we are deleting elements from the hash object with the help of the Hash.select() method. You can see that the method is deleting all the elements for which the method has returned false. This method is one of the examples of non-destructive methods because it is not creating changes in the self hash object.

Example 2:

=begin
  Ruby program to demonstrate select method
=end	

hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}

puts "Hash select implementation"

puts "Hash after select :#{hash1.select}"

puts "Self hash object : #{hash1}"

Output

Hash select implementation
Hash after select :#<Enumerator:0x000055fd5496c880>
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}

Explanation:

In the above code, you can observe that this method returns an enumerator when called without providing any block at the time of invocation.



Comments and Discussions!

Load comments ↻





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