è possibile convertire gli hash per sets e di eseguire il controllo utilizzando i metodi subset?
e superset?
(oi loro rispettivi alias <=
e >=
):
require 'set'
hash.to_set.superset?({}.to_set)
# => true
hash.to_set >= {a: 1}.to_set
# => true
{a: 2}.to_set <= hash.to_set
# => false
Aggiornamento: un punto di riferimento delle soluzioni proposte:
require 'fruity'
require 'set'
hash = ('aa'..'zz').zip('aa'..'zz').to_h
# {"aa"=>"aa", "ab"=>"ab", ...
find = ('aa'..'zz').zip('aa'..'zz').select { |k, _| k[0] == k[1] }.to_h
# {"aa"=>"aa", "bb"=>"bb", ...
compare(
toro2k: -> { hash.to_set >= find.to_set },
MarekLipka: -> { hash.merge(find) == hash },
CarySwoveland: -> { (find.to_a - hash.to_a).empty? },
ArupRakshit: -> { arr = hash.to_a; find.all? { |pair| arr.include?(pair) } }
)
Risultato:
Running each test 2 times. Test will take about 1 second.
MarekLipka is faster than toro2k by 3x ± 0.1
toro2k is faster than CarySwoveland by 39.99999999999999% ± 10.0%
CarySwoveland is faster than ArupRakshit by 1.9x ± 0.1
Matt, ti sembra di essere stato conferito con una [imbarazzo della scelta] (http: //dictionary.cambridge. org/Dizionario/britannico/un-imbarazzo-of-ricchezza). (Collegamento per coloro per i quali l'inglese è una seconda lingua). Ottenere quattro delle quattro risposte di qualità su SO è piuttosto raro. –