Hash.default = obj方法与Ruby中的示例

Hash.default = obj方法

在本文中,我们将研究Hash.default = obj Method。可以借助其名称来预测此方法的工作,但是它并不像看起来那样简单。好吧,我们将在其余内容中借助其语法和程序代码来理解此方法。

方法说明:

此方法是在ruby库中定义的公共实例方法,特别是针对Hash类。此方法用于设置默认值,并且在查找键时未找到键时将返回该值。请记住,您可以将procs设置为任何哈希对象的默认值。如果未设置默认值,则在找不到键或键不是哈希实例的一部分时将返回nil。

语法:

    Hash_object.default = object

Argument(s) 需要:

此方法不需要任何参数。此方法用于分配值。

范例1:

=begin
  Ruby program to demonstrate default method
=end	

hsh = Hash.new()hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"

puts "Hash default implementation"

hsh.default = "not available"
puts "Hash contents are : #{hsh}"

puts "Enter the key you want to find:"
ky = gets.chomp
puts "The value of #{ky} is #{hsh[ky]}"

输出结果

Hash default implementation
Hash contents are : {"color"=>"Black", "age"=>20, "school"=>"Angels' Academy Haridwar", "college"=>"Graphic Era University"}
Enter the key you want to find:
 animal
The value of animal is not available

说明:

在上面的代码中,您可以看到我们已经在new方法的帮助下设置了默认值。我们正在借助默认方法访问该默认值。默认值为“不可用”,只要在哈希对象中找不到键,就将返回此值。

范例2:

=begin
  Ruby program to demonstrate default method
=end	

hsh = Hash.new()hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"

puts "Hash default implementation"

hsh.default = proc do|hash,key|
hash = key+key
end

puts "Hash contents are : #{hsh}"

puts "Enter the key you want to find:"
ky = gets.chomp
puts "The value of #{ky} is #{hsh[ky]}"

输出结果

Hash default implementation
Hash contents are : {"color"=>"Black", "age"=>20, "school"=>"Angels' Academy Haridwar", "college"=>"Graphic Era University"}
Enter the key you want to find:
 animal
The value of animal is #<Proc:[email protected](repl):14>

说明:

在上面的代码中,您可以观察到我们正在尝试将proc设置为哈希对象的默认值。您还可以观察到我们没有得到理想的结果,因为您永远无法借助此方法将proc设置为任何哈希的默认值。