使用Ruby,什么是最有效的方法来检查,如果哈希任何按键阵列内匹配任何值 [英] Using Ruby, what is the most efficient way to check if any key in a hash matches any values within an Array

查看:174
本文介绍了使用Ruby,什么是最有效的方法来检查,如果哈希任何按键阵列内匹配任何值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在参数哈希键对元素的匹配数组进行比较。

例如:

  PARAMS = {键1,KEY2,KEY3}
params_to_match = [键2,KEY3]
 

我能做到这一点,但我敢肯定有一个更优雅的方式来实现同样的结果。

  params.each_key {|键|
  如果params_to_match.include?(key.to_s)
    返回
  结束
}
 

解决方案

不见得多的有效的,但也许更多的优雅的在某种意义上是:

 返回,除非(params.keys&安培; params_to_match).empty?
 

比你会的例子更有效的方式(在一般情况下,不一定有这样的一个小玩具的例子)是检查哈希是否包含关键字,因为时间看这些了实际上是恒定的,同时寻找起来从阵列是O(n)。所以,你的榜样会成为这样的事情:

  params_to_match.each {| P |如果params.has_key回来吗?(对)}
 

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
}

解决方案

Not necessarily more efficient but perhaps more elegant in some sense:

return unless (params.keys & params_to_match).empty?

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:

params_to_match.each { |p| return if params.has_key?(p) }

这篇关于使用Ruby,什么是最有效的方法来检查,如果哈希任何按键阵列内匹配任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆