Home » Ruby programming

Hash.dig() Method with Example in Ruby

Ruby Hash.dig() Method: Here, we are going to learn about the Hash.dig() Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 20, 2020

Hash.dig() Method

In this article, we will study about Hash.dig() 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 Hash class. This method works in a way that takes out the nested value stored after a sequence of key objects. dig method is invoked at every step of the traverse. 'nil' is returned when no value is found at any specific step.

Syntax:

    Hash_object.dig(obj, ...)

Argument(s) required:

You can pass any number of arguments inside this method. However, at least one argument is mandatory.

Example 1:

=begin
  Ruby program to demonstrate dig method
=end	

hsh = {country:{state:{city:"Haridwar"}}}

puts "Hash dig implementation"

if(hsh.dig(:country,:state,:city))
	puts "The value is #{hsh.dig(:country,:state,:city)}"
else
	puts "Value not available"
end

Output

Hash dig implementation
The value is Haridwar

Explanation:

In the above code, you can observe that we are digging some value from the hash object. We have passed three arguments inside the dig method namely country, state, and city. The method has traversed the hash object until it does not find the value. The method must have returned 'nil' if no value is found inside the hash object during the process of digging.

Example 2:

=begin
  Ruby program to demonstrate dig method
=end

hsh = { foo: [10, 11, 12] }

puts "Hash dig implementation"

puts hsh.dig(:foo, 1)              
puts hsh.dig(:foo, 1, 0)           
puts hsh.dig(:foo, :bar)   	

Output

Hash dig implementation
11
Integer does not have #dig method
(repl):10:in `dig'
(repl):10:in `<main>'

Explanation:

In the above code, you can observe that we are digging value from the hash object which has a key and whose value is an integer array. You can utmost one value along with one key in case of the value of array type.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.