Ruby中带有示例的Hash.values方法

Hash.values方法

在本文中,我们将研究Hash.values方法。可以假设该方法的工作是由于其非常通用的名称,但也存在一些隐藏的复杂性。让我们阅读其定义并在语法和程序代码的帮助下了解其实现。

方法说明:

该方法是Public实例方法,属于Hash类,它位于Ruby语言库中。此方法的工作方式是返回一个包含哈希对象中存在的所有值的数组。此方法遍历整个哈希对象,并将值存储在要返回的数组中并带有单独的索引。Hash.values如果哈希对象内部不存在任何值,则该方法将返回一个空数组实例。

语法:

Hash_object.values

Argument(s) 需要:

此方法不带任何参数。它返回一个包含所有哈希对象值的哈希。

范例1:

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

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

puts "Hash.values implementation"

ary = hsh.values

puts "Values present in the hash are:"

ary.each do |val|
	puts val
end

输出结果

Hash.values implementation
Values present in the hash are:
red
Nainital
Grapes
red
ladoo

说明:

在上面的代码中,您可以观察到我们可以通过 Hash.values ()方法获得特定散列对象中的所有值。您可以看到,所有的值都存储在一个可以显示的数组对象中。

范例2:

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

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

puts "Hash.values implementation"

ary = hsh.values

puts "Values present in the hash are:"

puts "#{ary}"

输出结果

Hash.values implementation
Values present in the hash are:
[["red", "blue", "green"], "Nainital", "Grapes", "red", "ladoo"]

说明:

在上面的代码中,您可以观察到可以通过 Hash.values ()方法从散列对象中获取所有的值。在上面的代码中,您可以观察到一个多维数组对象已经被返回,因为散列对象包含一个存储在特定键中的值数组。