當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。