Home » Ruby programming

Hash.default_proc Method with Example in Ruby

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

Hash.default_proc Method

In this article, we will study about Hash.default_proc 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 Ruby library especially for Hash class. This method works in a way that if the hash new method has been invoked with a block then it will return that block when the default_proc() method has been invoked. This method will return nil if the new method has been invoked without passing any block. You will understand the concept in a broader way when you will go through its examples.

Syntax:

    Hash_object.default_proc

Argument(s) required:

This method does not require any argument.

Example 1:

=begin
  Ruby program to demonstrate default_proc method
=end	

h = Hash.new {|h,k| h[k] = k*k }

puts "default_proc implementation:"   

p = h.default_proc                 
a = []                             

puts "#{p.call(a, 2)}"
puts "The elements in 'a' array are: #{a}" 

Output

default_proc implementation:
4
The elements in 'a' array are: [nil, nil, 4]

Explanation:

In the above code, you can observe that we are invoking a new method along with the block and that block is doing nothing rather than returning the double of the element passed. When we are calling the proc p which is containing the default proc value of Hash object along with the index and block value than at the time of printing the array, we are getting the block returned value stored at the index position.

Example 2:

=begin
  Ruby program to demonstrate default_proc method
=end	

h = Hash.new 

puts "default_proc implementation:"   

p = h.default_proc                 
a = []                             

puts "#{p.call(a, 2)}"
puts "The elements in 'a' array are: #{a}"            

Output

default_proc implementation:
undefined method `call' for nil:NilClass
(repl):12:in `<main>'

Explanation:

In the above code, you can observe that when the new method is invoked without a block then the variable 'p' is not considered as a proc because the hash default_proc method has returned 'nil'.



Comments and Discussions!

Load comments ↻





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