我有一个哈希。在其中,每个键的值是一个数组。我想测试一个值是否在其中一个数组中,如果是,则测试它对应于哪个键。例如,假设我正在编写一个带有命令列表的命令行程序,并且每个命令都有一些昵称,如下所示:
commands = {
:exit => ['exit', 'ex'],
:start_car => ['start_engine', 'start'],
:accelerate => ['speed_up', 'accelerate'],
:help => ['help', '?']
}
所以如果我想开车,我可以输入start_engine
或start
,两者都可以。
我们还要说我需要一个函数来测试给定的字符串是否是命令的名称。如果没有,请返回false
。如果是这样,请返回命令的名称,如下所示:
def is_command? string
if # string is a nickname
# return the key to which it belongs, i.e. 'ex' to :exit
else
return false
end
end
我尝试浏览Hashes and Arrays的功能列表,但我找不到任何东西,我甚至无法开始考虑如何使用Google这样的东西。任何帮助都会非常受欢迎。
答案 0 :(得分:5)
使用find
:
commands = {:exit => ['exit', 'ex'], :start_car => ['start_engine', 'start'], :accelerate => ['speed_up', 'accelerate'], :help => ['help', '?']}
commands.find { |key,value| value.include?( '?' ) }
> [:help, ["help", "?"]]
答案 1 :(得分:2)
最好建立一个反向哈希,比如
commands = {
:exit => ['exit', 'ex'],
:start_car => ['start_engine', 'start'],
:accelerate => ['speed_up', 'accelerate'],
:help => ['help', '?'],
}
command_for = {}
commands.each_pair do
| cmd, names |
names.each { |name| command_for[name] = cmd }
end
puts command_for['start']
puts command_for['help']
puts command_for['?']
<强>输出强>
start_car
help
help