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


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

Hash.values_at() 方法

在本文中,我們將研究 Hash.values_at() 方法。可以假設該方法的用法原理,因為它的名稱非常常見,但也存在一些隱藏的複雜性。讓我們在語法和程序代碼的幫助下閱讀它的定義並理解它的實現。

方法說明:

該方法是一個公共實例方法,屬於 Ruby 語言庫中的 Hash 類。此方法的用法方式是返回一個數組,該數組包含在調用時與該方法一起傳遞的鍵的所有值。此方法遍曆整個哈希對象並找到指定的鍵的特定值。如果 Hash.values_at() 方法給定的鍵不存在於散列對象中,則該方法將返回一個空數組實例。

用法:

    Hash_object.values_at(keys, ...)

所需參數:

此方法可以接受任意數量的參數。這些參數隻不過是您要查找其值的鍵。

範例1:

=begin
  Ruby program to demonstrate Hash.values_at method
=end	

hsh = {"colors"  => "red","city"=>"Nainital", "Fruit" => "Grapes", "anything"=>"red","sweet"=>"ladoo"}

puts "Hash.values_at implementation"

puts "Enter the first key:"
ky1 = gets.chomp

puts "Enter the second key:"
ky2 = gets.chomp

puts "Enter the third key:"
ky3 = gets.chomp

ary = hsh.values_at(ky1,ky2,ky3)

puts "values present in the array are:"
ary.each do |key|
	puts key
end

輸出

Hash.values_at implementation
Enter the first key:
 colors
Enter the second key:
 city
Enter the third key:
 Fruit
values present in the array are:
red
Nainital
Grapes

說明:

在上麵的代碼中,您可以觀察到我們可以嘗試借助 Hash.values_at() 方法來獲取值。您可以看到該方法返回的數組包含該方法傳遞的所有鍵值。

範例2:

=begin
  Ruby program to demonstrate Hash.values_at method
=end	

hsh = {"colors"  => "red","city"=>"Nainital", "Fruit" => "Grapes", "anything"=>"red","sweet"=>"ladoo"}

puts "Hash.values_at implementation"

ary = hsh.values_at("life","bike")

puts "values present in the array are:"
ary.each do |key|
	puts key
end

輸出

Hash.values_at implementation
values present in the array are:

說明:

在上麵的代碼中,您可以觀察到我們正在嘗試借助 Hash.values_at() 方法從哈希對象中獲取值。您可以看到,當用戶傳遞的鍵不在哈希中時,該方法返回一個空數組實例。



相關用法


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