Is there a better way to judge if one ruby ​​hash is in another?

for example, hash a , {:name=>'mike',:age=>27,:gender=>'male'} and hash b is {:name=>'mike'}

I am wondering if there is a better way to judge if hash b is inside hash a instead of comparing each key one by one?

I found a way to do this, is it more efficient than comparing keys?

a.merge (b) == a

+4
source share
2 answers

I like the intersection calculation approach you are trying to do:

 a = { :a => :b, :c => :d } b = { :e => :f, :a => :b } c = { :a => :f, :e => :c } (a.to_a & b.to_a).any? # => true (a.to_a & c.to_a).any? # => false 
+5
source
 b.all? do |key, value| a.include? key && a[key] == value end 

This cycle is linear in size b, since both stages within the cycle take (on average) constant time.

+1
source

Source: https://habr.com/ru/post/1383362/


All Articles