当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Hash.delete()用法及代码示例


Hash.delete() 方法

在本文中,我们将研究 Hash.delete() 方法。这种方法的用法原理可以通过它的名字来预测,但它并不像看起来那么简单。那么,我们将在其余内容中借助其语法和程序代码来理解该方法。

方法说明:

该方法是ruby库中专门为Hash类定义的公共实例方法。此方法的用法方式是删除在调用时与方法一起传递的键的键值对。如果未找到该键,则返回 'nil'。为了避免 'nil' 值,您可以随方法传递一个块,然后在找不到键的情况下返回该值的结果。

用法:

    Hash_object.delete(object)
    or
    Hash_object.delete(object){block}

所需参数:

您最多可以通过此方法传递一个对象。可以给出一个可选块以避免 '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"}

说明:

在上面的代码中,您可以观察到,当在 hash 对象中找不到 key 时,则块已被执行并返回了块处理值。这在块的帮助下是可能的,否则必须从 delete() 方法返回 'nil' 值。



相关用法


注:本文由纯净天空筛选整理自 Hash.delete() Method with Example in Ruby。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。