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
}
Use
&
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.I think the best combination of elegant and efficient would be
If you have ActiveSupport, you could do
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: