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


Ruby Hash.fetch()用法及代碼示例

Hash.fetch() 方法

在本文中,我們將研究 Hash.fetch() 方法。這種方法的用法原理可以通過它的名字來預測,但它並不像看起來那麽簡單。那麽,我們將在其餘內容中借助其語法和程序代碼來理解該方法。

方法說明:

該方法是ruby庫中專門為Hash類定義的公共實例方法。此方法需要通過此方法獲取其值的鍵。此方法的用法方式是為給定的一個或多個鍵從散列對象返回一個或多個值。如果在散列實例中找不到鍵,則結果取決於完成的方法調用的類型。下麵列出了可能的方法調用:

  • 沒有任何其他參數:如果沒有提供其他參數並且未找到 key ,則該方法將拋出 "KeyError" 異常。
  • 與其他參數(s):另一個參數被視為默認參數。如果未找到該鍵,則該方法將返回該默認參數。
  • 帶塊:如果提供了塊但未找到 key ,則將運行該塊並在未找到 key 的情況下返回結果。

用法:

    Hash_object.fetch(…,[default]);
    or
    Hash_object_fetch(key(s))
    or
    Hash_object_fetch{|key| block}

所需參數:

傳遞參數沒有限製。您可以根據您的要求傳遞參數。最後一個參數將始終被視為默認參數。

範例1:

=begin
  Ruby program to demonstrate fetch method
=end	

hash1={"color"=>"Black","object"=>"phone","love"=>"mom","fruit"=>"Kiwi","vege"=>"potato"}

puts "Hash.fetch implementation"

puts "Enter the key you want to search:"
ky = gets.chomp

if(hash1.fetch(ky))
	puts "Key found successfully. The value is #{hash1.fetch(ky)}"
else
	puts "No key found"
end

輸出

RUN 1:
Hash.fetch implementation
Enter the key you want to search:
 color
Key found successfully. The value is Black

RUN 2:
Hash.fetch implementation
Enter the key you want to search:
 velvet
key not found:"velvet"
(repl):12:in `fetch'
(repl):12:in `<main>'

說明:

在上麵的代碼中,您可以簡單地觀察到我們使用用戶詢問的 key 調用了該方法。在運行 2 中,您可能會看到在散列中找不到鍵時拋出異常。

範例2:

=begin
  Ruby program to demonstrate fetch method
=end	

hash1={"color"=>"Black","object"=>"phone","love"=>"mom","fruit"=>"Kiwi","vege"=>"potato"}

puts "Hash.fetch implementation"

puts "Enter the key you want to search:"
ky = gets.chomp

puts "The value of #{ky} is #{hash1.fetch(ky,"Not found")}"

輸出

Hash.fetch implementation
Enter the key you want to search:
 cloth
The value of cloth is Not found

說明:

在上麵的代碼中,您可以觀察到我們在方法內部傳遞了一個默認參數和鍵。可以看到在hash實例中沒有找到key時,返回的是默認對象。

範例3:

=begin
  Ruby program to demonstrate fetch method
=end	

hash1={"color"=>"Black","object"=>"phone","love"=>"mom","fruit"=>"Kiwi","vege"=>"potato"}

puts "Hash.fetch implementation"

puts "Enter the key you want to search:"
ky = gets.chomp

puts "The value of #{ky} is #{hash1.fetch(ky){|ky| "Sorry! #{ky} is missing"}}"

輸出

Hash.fetch implementation
Enter the key you want to search:
 cloth
The value of cloth is Sorry! cloth is missing

說明:

在上麵的代碼中,您可以觀察到我們正在與方法一起傳遞一個塊。當在散列對象中找不到鍵時,該塊已運行並已返回其值。



相關用法


注:本文由純淨天空篩選整理自 Hash.fetch() Method with Example in Ruby。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。