使用Ruby,什么是最有效的方法来检查,如果哈希任何按键阵列内匹配任何值阵列、方法来、最有效、按键

2023-09-11 07:18:20 作者:£醉色↘染红颜╮

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

例如:

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

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

  params.each_key {|键|
  如果params_to_match.include?(key.to_s)
    返回
  结束
}
 
声而不凡 东微RUBY系列旗舰版数字音频处理器 闪耀发布

解决方案

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

 返回,除非(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) }