Ruby中带有示例的Hash.include?()方法
Hash.include?()方法
在本文中,我们将研究Hash.include?()方法。由于该方法的名称完全不同,因此无法进行假设。让我们阅读其定义并在语法和程序代码的帮助下了解其实现。
方法说明:
该方法是Public实例方法,属于Hash类,它位于Ruby语言库中。此方法用于检查键是否是特定Hash实例的一部分。它将搜索整个哈希,并根据其搜索结果。让我们来看一下语法,并演示该方法的程序代码。
如果您正在考虑它将返回什么,那么让我告诉您,它将返回一个布尔值。如果在哈希表中找到键,则返回值将为true;如果找不到哈希表实例的一部分,则返回值为false。
语法:
Hash_instance.include?(key)
Argument(s)
需要:
此方法仅使用一个参数,而该参数不过是我们要检查其状态的键。
范例1:
=begin Ruby program to demonstrate Hash.include method =end hsh = {"colors" => "red", "letters" => "a", "Fruit" => "Grapes"} puts "Hash.include implementation:" puts "Enter the Key you want to search:" ky = gets.chomp if (hsh.include?(ky)) puts "Key found successfully" else puts "Key not found!" end
输出结果
Hash.include implementation: Enter the Key you want to search: colors Key found successfully
说明:
在上面的代码中,您可以观察到我们在普通的Hash实例上调用include方法。当它在用户输入的哈希对象中发现键存在时,它返回true。
范例2:
=begin Ruby program to demonstrate Hash.include method =end hsh = {"colors" => "red", "letters" => "a", "Fruit" => "Grapes"} hsh1 = {"cars" => "800", "bike" => "pulsar", "phone" => "A50"} hsh2 = {"one"=> hsh, "two" => hsh1} puts "Hash.include implementation:" puts "Enter the Key you want to search:" ky = gets.chomp if (hsh2.include?(ky)) puts "Key found successfully" else puts "Key not found!" end
输出结果
RUN 1: Hash.include implementation: Enter the Key you want to search: bike Key not found! RUN 2: Hash.include implementation: Enter the Key you want to search: two Key found successfully
说明:
在以上程序中,您可以验证include方法不适用于作为多个Hash实例集合的Hash实例。即使对象是Hash实例的一部分,它也会返回false。