Hash.delete()方法以及Ruby中的示例
Hash.delete()
方法
在本文中,我们将研究Hash.delete()
方法。可以借助其名称来预测此方法的工作,但是它并不像看起来那样简单。好吧,我们将在其余内容中借助其语法和程序代码来理解此方法。
方法说明:
此方法是在ruby库中定义的公共实例方法,特别是针对Hash类。此方法的工作方式是删除调用时与该方法一起传递的键的键-值对。如果找不到该键,则返回'nil'。为了避免'nil'值,您可以将一个块与该方法一起传递,然后在找不到键的情况下返回该值的结果。
语法:
Hash_object.delete(object) or Hash_object.delete(object){block}
Argument(s)
需要:
您最多可以使用此方法传递一个对象。为了避免返回“nil”值,可以给出一个可选的块。
范例1:
=begin Ruby program to demonstrate delete method =end hsh = Hash.new()hsh["color"] = "Black" hsh["age"] = 20 hsh["school"] = "Angels' Academy Haridwar" hsh["college"] = "Graphic Era University" puts "Hash delete implementation" puts "Enter the key you want to delete:" ky = gets.chomp if(hsh.delete(ky)) puts "Key deleted successfully" else puts "Key not found" end puts "Hash contents are : #{hsh}"
输出结果
Hash delete implementation Enter the key you want to delete: school Key deleted successfully Hash contents are : {"color"=>"Black", "age"=>20, "college"=>"Graphic Era University"}
说明:
在上面的代码中,您可以观察到该方法正在哈希对象上创建永久更改,并且键及其值已从哈希对象中删除。
范例2:
=begin Ruby program to demonstrate delete method =end hsh = Hash.new()hsh["color"] = "Black" hsh["age"] = 20 hsh["school"] = "Angels' Academy Haridwar" hsh["college"] = "Graphic Era University" puts "Hash delete implementation" puts "Enter the key you want to delete:" ky = gets.chomp puts "#{hsh.delete(ky){|ky|"#{ky} not found"}}" puts "Hash contents are : #{hsh}"
输出结果
Hash delete implementation Enter the key you want to delete: car car not found Hash contents are : {"color"=>"Black", "age"=>20, "school"=>"Angels' Academy Haridwar", "college"=>"Graphic Era University"}
说明:
在上面的代码中,您可以观察到,当在哈希对象中找不到该键时,该块已被执行,并且该块的处理值已返回。借助块可以做到这一点,否则必须从方法中返回'nil'值。delete()