24

I am using Ruby on Rails 3.1.0 and I would like to check if an hash is "completely" included in another hash and return a boolean value.

Say I have those hashes:

hash1 = {
  :key1 => 'value1',
  :key2 => 'value2',
  :key3 => 'value3'
}

hash2 = {
  :key1 => 'value1',
  :key2 => 'value2',
  :key3 => 'value3',
  :key4 => 'value4',
  :key5 => 'value5',
  ...
}

I would like to check if the hash1 is included in the hash2 even if in the hash2 there are more values than hash1 (in the above case the response that I am looking for should be true)? Is it possible to do that by using "one only code line"\"a Ruby method"?

1
  • 1
    Perhaps you can merge hash1 into hash2 (hash2.merge(hash1)) and see if it changed. That's a very naive way of doing it, but if it's one line of code you want, it's probably the simplest way.
    – user824425
    Sep 28, 2011 at 14:37

7 Answers 7

45

That will be enough

(hash1.to_a - hash2.to_a).empty?
2
  • Nice. That's why I added the "I can think of" part to my answer ;-) Sep 28, 2011 at 15:17
  • Brilliant! I just spent an hour playing with collect include? values_at and friends... with no reasonable result. To finally hit this answer. So simple.
    – Kocur4d
    Mar 30, 2013 at 2:41
5

The easiest way I can think of would be:

hash2.values_at(*hash1.keys) == hash1.values
5

the more elegant way is to check the equality when one hash merge another.

e.g. rewrite Hash include? instance method for this.

class Hash
  def include?(other)
    self.merge(other) == self
  end
end

{:a => 1, :b => 2, :c => 3}.include? :a => 1, :b => 2 # => true
3

There is a way:

hash_2 >= hash_1

Alternatively:

hash_1 <= hash_2

More info in this post: https://olivierlacan.com/posts/proposal-for-a-better-ruby-hash-include/

1

The most efficient and elegant solution I've found - with no intermediary arrays, or redundant loops.

class Hash
  alias_method :include_key?, :include?

  def include?(other)
    return include_key?(other) unless other.is_a?(Hash)
    other.all? do |key, value|
      self[key] == value
    end
  end
end

Since Ruby 2.3 you can use built-in Hash#<= method.

1

Since Ruby 2.3, you can do this:

hash1 <= hash2
0

I am not sure if I understand the inclusion idea in hash. To see if it has the same keys(usual problem). All keys in hash1 are included in hash2: hash1.keys - hash2.keys == []

Then if you want to compare those values do as suggested in the previous post: hash1.values - hash2.values_at(*hash1.keys) == []

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.