Search code examples
rubyhashsubsetcontain

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

Solution

  • 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