当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。