Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash check is subset?

How can I tell if if a Ruby hash is a subset of (or includes) another hash?

For example:

hash = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7}
hash.include_hash?({})            # true
hash.include_hash?({f: 6, c: 3})  # true
hash.include_hash?({f: 6, c: 1})  # false
like image 836
ma11hew28 Avatar asked Apr 17 '14 14:04

ma11hew28


4 Answers

Since Ruby 2.3 you can also do the following to check if this is a subset

hash = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7}
{} <= hash           # true
{f: 6, c: 3} <= hash # true
{f: 6, c: 1} <= hash # false
like image 137
Pieter Avatar answered Nov 09 '22 15:11

Pieter


The solution that came into my mind use Hash#merge method:

class Hash
  def include_hash?(hash)
    merge(hash) == self
  end
end

hash = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7}
hash.include_hash?({})
# => true
hash.include_hash?(f: 6, c:3)
# => true
hash.include_hash?(f: 6, c:1)
# => false
like image 44
Marek Lipka Avatar answered Nov 09 '22 17:11

Marek Lipka


Array difference seems easiest:

class Hash
  def include_hash?(h)
    (h.to_a - to_a).empty?
  end
end

h = {a: 1, b: 2}
h.include_hash?({b: 2}) #=> true
h.include_hash?({b: 3}) #=> false
like image 31
Cary Swoveland Avatar answered Nov 09 '22 15:11

Cary Swoveland


You could convert the hashes to sets and than perform the check using the methods subset? and superset? (or their respective aliases <= and >=):

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

Update: a benchmark of the proposed solutions:

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) } }
)

Result:

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
like image 37
toro2k Avatar answered Nov 09 '22 15:11

toro2k