使用 Ruby,检查哈希中的任何键是否与数组中的任何值匹配的最有效方法是什么
我想将参数哈希中的键与元素数组进行比较以进行匹配。
例如:
params = {"key1", "key2", "key3"}
params_to_match = ["key2","key3"]
我可以这样做,但我确信有一种更优雅的方法可以达到相同的结果
params.each_key{|key|
if params_to_match.include?(key.to_s)
return
end
}
I want to compare the keys in a hash of parameters against an array of elements for a match.
For example:
params = {"key1", "key2", "key3"}
params_to_match = ["key2","key3"]
I could do this, but I'm sure there is a much more elegant way to acheive the same result
params.each_key{|key|
if params_to_match.include?(key.to_s)
return
end
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不一定更高效,但在某种意义上可能更优雅:
比您的示例更有效的方式(在一般情况下,不一定是这样一个小玩具示例)检查哈希是否包含键,因为从数组中查找它们时查找这些键的时间实际上是恒定的,为 O(n)。所以,你的例子会变成这样:
Not necessarily more efficient but perhaps more elegant in some sense:
A more efficient way than your example would (in the general case, not necessarily with such a small toy example) be to check whether the hash contains the keys, since the time to look those up is practically constant while looking them up from the array is O(n). So, your example would become something like this:
使用
&
Use
&
我认为优雅和高效的最佳结合是
如果你有 ActiveSupport,你可以这样做
I think the best combination of elegant and efficient would be
If you have ActiveSupport, you could do
这是伪代码中的快速算法。
该算法假设键和输入一开始就已排序,执行时间为 O(n+m),n 和 m 是键和输入的计数。我将让您将其翻译为 Ruby,但请密切注意
find()
函数;它必须从上一次迭代中找到的位置开始搜索,而不是在键的开头。否则你的键数就会减少到 O(n^2+m), n 。Here's a fast algorithm in psedudocode.
This algorithm, assuming the keys and the input are sorted to begin with, performs in O(n+m), n and m being the count of keys and input. I'll leave it for you to translate that to Ruby, but pay close attention to the
find()
function; it must start its search at the position found in the previous iteration, not at the start of keys. Otherwise you're down to O(n^2+m), n the count of keys.