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


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


Hash.fetch_values() 方法

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

方法說明:

該方法是ruby庫中專門為Hash類定義的公共實例方法。此方法需要通過此方法獲取其值的鍵。此方法的用法方式是返回包含給定鍵或鍵的哈希對象中的一個或多個值的數組實例。如果在散列對象中找不到鍵,則該方法拋出異常,稱為 "keyless" 異常。為了對鍵值進行某種操作,您甚至可以使用該方法傳遞一個塊。

用法:

    Hash_object.fetch_values(key1, key2,…, keyn)
    or
    Hash_object_fetch_values(key1, key2,…, keyn){|key| block}

所需參數:

傳遞參數沒有限製。您可以根據您的要求傳遞參數。

範例1:

=begin
  Ruby program to demonstrate fetch_values method
=end	

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

puts "Hash.fetch_values implementation"

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

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

if(hash1.fetch_values(ky1,ky2))
	puts "Key found successfully. The values ar #{hash1.fetch_values(ky1,ky2)}"
else
	puts "One of the keys are missing"
end

輸出

RUN 1:
Hash.fetch_values implementation
Enter the first key you want to search:
 color
Enter the second key you want to search:
 object
Key found successfully. The values ar ["Black", "phone"]

RUN 2:
Hash.fetch_values implementation
Enter the first key you want to search:
 cloth
Enter the second key you want to search:
 color
key not found:"cloth"
(repl):15:in `fetch_values'
(repl):15:in `<main>'

說明:

在上麵的代碼中,您可能會觀察到此方法返回一個值數組。這些值隻不過是與方法一起傳遞的鍵的值。在運行 2 中,您可以觀察到即使缺少單個鍵,該方法也會拋出 "Keyless" 異常

範例2:

=begin
  Ruby program to demonstrate fetch_values method
=end	

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

puts "Hash.fetch_values implementation"

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

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

if(hash1.fetch_values(ky1,ky2){|ky| ky.upcase})
	puts "Key found successfully. The values are #{hash1.fetch_values(ky1,ky2){|ky| ky.upcase}}"
else
	puts "One of the keys are missing"
end

輸出

Hash.fetch_values implementation
Enter the first key you want to search:
 color
Enter the second key you want to search:
 car
Key found successfully. The values are ["Black", "CAR"]

說明:

在上麵的代碼中,您可以觀察到當我們傳遞一個塊時,未找到的鍵被轉換為大寫。這可以保護我們免於獲得異常。



相關用法


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