我想在参数哈希键对元素的匹配数组进行比较。
例如:
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) }
上一篇:水平翻转一个比特位图线位图、水平