Ruby程序检查哈希是否包含指定的键
检查哈希是否包含键
给定一个哈希和键,我们必须检查哈希是否包含键。
哈希是相同键及其值的集合。哈希是整数和对象类型的组合。您可以通过以下方式声明哈希:
hash_name = {key_name1:value1, key_name2:value2, ...}可以使用.key?轻松检查已定义哈希中是否存在键。关键词。
使用的方法:
puts:
此方法用于将消息显示在屏幕上,以方便用户使用。
.key?:
.key?方法用于在哈希中查找键。它用于从哈希引用值。如果未找到键,则返回false,否则返回true。
Ruby代码检查哈希是否包含键
=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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志