我有一个所有可能排名的引用散列,如下所示:
hash = {
bronze: 0,
silver: 1,
gold: 2,
platinum: 3,
diamond: 4
}
我得到一个给定的排名,以及其他现有排名的数组,我需要确定给定排名是否存在“邻居”。我会尝试一个例子:
given_rank = 'gold'
existing_ranks = ['silver', 'platinum']
这应该返回 true
- 白银在黄金正下方,铂金在正上方 - 两个邻居都存在。
given_rank = 'gold'
existing_ranks = ['silver', 'diamond']
这应该返回 false
- 上面缺少铂金
这是我现在拥有的:
user_rank = hash[given_rank]
higher = hash.invert[user_rank + 1]
lower = hash.invert[user_rank - 1]
if existing_ranks.include?(higher) && existing_ranks.include?(lower)
# do something
else
# do another thing
end
是否有更有效/高效/ruby 的方式来解决这个问题?
最佳答案
使用连续索引之间的简单数学关系,您可以编写:
n1, n2 = hash.values_at(*existing_ranks)
are_neighbors = (n1 - n2).abs == 2 && hash[given_rank] == (n1 + n2) / 2
关于ruby - 确定邻居是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33212734/