开发者

How to check if an hash is "completely" included in another hash?

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 possi开发者_JAVA技巧ble to do that by using "one only code line"\"a Ruby method"?


That will be enough

(hash1.to_a - hash2.to_a).empty?


The easiest way I can think of would be:

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


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


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/


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.


Since Ruby 2.3, you can do this:

hash1 <= hash2


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) == []

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜