Hash.assoc() 方法
在本文中,我們將研究 Hash.assoc() 方法。無法假設該方法的用法原理,因為它的名稱完全不同。讓我們在語法和程序代碼的幫助下閱讀它的定義並理解它的實現。
方法說明:
該方法是一個公共實例方法,屬於 Ruby 語言庫中的 Hash 類。此方法用於檢查對象(鍵值)是否是特定 Hash 實例的一部分,並且該 Hash 實例可以或不能是正常的 Hash 實例。如果不正常,則說明Hash實例是多個Array實例及其鍵的Hash,也可以說是多個鍵值的集合,本身就是Array類的對象。讓我們通過語法並演示此方法的程序代碼。
如果您正在考慮它將返回什麽,那麽讓我告訴您,它將返回第一個包含的 Hash 實例,它發現鍵值對的存在。如果它沒有在任何哈希中找到對象,它將返回 "nil"。
用法:
Hash_instance.assoc(obj)
所需參數:
這個方法隻接受一個參數,而這個參數隻不過是一個我們想要檢查其存在的對象。
範例1:
=begin
Ruby program to demonstrate Hash.assoc method
=end
hsh = {"colors" => ["red", "blue", "green"],
"letters" => ["a", "b", "c" ], "Fruit" => ["Banana","Kiwi","Grapes"]}
puts "Hash.assoc implementation:"
puts "Enter the Key you want to search:"
ky = gets.chomp
if (hsh.assoc(ky))
puts "Key found successfully"
puts "Values are:#{hsh.assoc(ky)}"
else
puts "Key not found!"
end
輸出
RUN 1: Hash.assoc implementation: Enter the Key you want to search: colors Key found successfully Values are:["colors", ["red", "blue", "green"]] RUN 2: Hash.assoc implementation: Enter the Key you want to search: veges Key not found!
說明:
在上麵的代碼中,可以發現我們調用了assoc()方法的Hash實例並不是普通的Hash實例。它是多個 Array 實例及其特定鍵的集合。它使用找到用戶輸入的鍵的鍵返回整個 Array 實例。
範例2:
=begin
Ruby program to demonstrate Hash.assoc method
=end
hsh = {"color"=> "green","vege"=> "papaya"}
puts "Hash assoc implementation:"
puts hsh.assoc("color")
輸出
Hash assoc implementation: color green
說明:
在上麵你可以驗證 assoc() 方法也適用於普通的 Hash 實例。如果鍵是 Hash 實例的一部分,它將返回鍵值對。
相關用法
- Ruby Hash.rassoc(obj)用法及代碼示例
- Ruby Hash.keep_if用法及代碼示例
- Ruby Hash.fetch_values()用法及代碼示例
- Ruby Hash.delete_if用法及代碼示例
- Ruby Hash.fetch()用法及代碼示例
- Ruby Hash.each用法及代碼示例
- Ruby Hash.keys用法及代碼示例
- Ruby Hash.transform_keys用法及代碼示例
- Ruby Hash.each_key用法及代碼示例
- Ruby Hash.insert()用法及代碼示例
- Ruby Hash.values_at()用法及代碼示例
- Ruby Hash.rehash用法及代碼示例
- Ruby Hash.each_value用法及代碼示例
- Ruby Hash.values用法及代碼示例
- Ruby Hash.replace()用法及代碼示例
- Ruby Hash.compact用法及代碼示例
- Ruby Hash.reject用法及代碼示例
- Ruby Hash.select用法及代碼示例
- Ruby Hash.flatten用法及代碼示例
- Ruby Hash.invert用法及代碼示例
注:本文由純淨天空篩選整理自 Hash.assoc() Method with Example in Ruby。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。