密钥哈希
检查哈希是否包含密钥 (Checking hash contains a key or not)
Given a hash and key, we have to check whether hash contains the key or not.
给定一个哈希和密钥,我们必须检查哈希是否包含密钥。
A hash is a collection of identical keys and their values. Hashes are the combination of integer and the object type. You can declare a hash in the following way:
哈希是相同键及其值的集合。 哈希是整数和对象类型的组合。 您可以通过以下方式声明哈希:
hash_name = {key_name1:value1, key_name2:value2, ...}
The existence of a key in a defined hash can be easily checked using .key? keyword.
可以使用.key?轻松检查已定义哈希中是否存在键。 关键词。
Methods used:
使用的方法:
puts:
放置 :
This method is employed for putting the message on the screen for user convenience.
为了方便用户,此方法用于将消息显示在屏幕上。
.key?:
。键? :
.key? method is used to find a key within a hash. It is employed for referencing value from hash. If the key is not found it returns false, otherwise true.
。键? 方法用于在哈希中查找键。 它用于从哈希引用值。 如果未找到密钥,则返回false,否则返回true。
Ruby代码检查哈希是否包含密钥 (Ruby code to check whether hash contains a key or not)
=begin
Ruby program to check whether a hash contains the
specified key or not.
=end
# declaring hash
hash={apple:1,mango:2,banana:3,orange:4,babypink:5}
#checking keys
puts hash.key?(:apple)
puts hash.key?(:one)
puts hash.key?(:orange)
puts hash.key?(:green)
puts hash.key?(:includehelp)
#checking through conditions
if(hash.key?(:apple))
puts "hash contains the key apple"
else
puts "hash doesnt contain the key apple"
end
if(hash.key?(:one))
puts "hash contains the key one"
else
puts "hash doesnt contain the key one"
end
if(hash.key?(:orange))
puts "hash contains the key orange"
else
puts "hash doesnt contain the key orange"
end
if(hash.key?(:green))
puts "hash contains the key green"
else
puts "hash doesnt contain the key green"
end
if(hash.key?(:includehelp))
puts "hash contains the key includehelp"
else
puts "hash doesnt contain the key includehelp"
end
Output
输出量
true
false
true
false
false
hash contains the key apple
hash doesnt contain the key one
hash contains the key orange
hash doesnt contain the key green
hash doesnt contain the key includehelp
翻译自: https://www.includehelp.com/ruby/check-whether-the-hash-contains-specified-key-or-not.aspx
密钥哈希