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 红包祝福语简短10字
18 周六早晨祝福语简短