4 Answers
4

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:

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.

FYI, you misinterpreted the question and then edited the title to match what you thought the question was. Also, why would the keys of a hash be already sorted? Using hash lookup is way faster than this.
–
mckeedMay 5 '10 at 2:48

it depends on how ruby implements the hash map, but if it was, say, a search-tree then traversing them would yield them in a sorted order. if they're not sorted then sort them: that would change the performance to O(n log n) + O(m), or big-theta of n + O(m) depending on the sort algorithm.
–
wilhelmtellMay 5 '10 at 3:28