给定一个哈希和键,我们必须检查哈希是否包含键。
哈希是相同键及其值的集合。哈希是整数和对象类型的组合。您可以通过以下方式声明哈希:
hash_name = {key_name1:value1, key_name2:value2, ...}
可以使用.key?轻松检查已定义哈希中是否存在键。关键词。
使用的方法:
puts:
此方法用于将消息显示在屏幕上,以方便用户使用。
.key?:
.key?方法用于在哈希中查找键。它用于从哈希引用值。如果未找到键,则返回false,否则返回true。
=begin Ruby program to check whether a hash contains the specified key or not. =end #声明哈希 hash={apple:1,mango:2,banana:3,orange:4,babypink:5} #检查按键 puts hash.key?(:apple) puts hash.key?(:one) puts hash.key?(:orange) puts hash.key?(:green) puts hash.key?(:includehelp) #检查条件 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 nhooo" else puts "hash doesnt contain the key nhooo" end
输出结果
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 nhooo