Determine if hash contains any key from a set of keys?

13,031

Solution 1

Here is how you get all of the matching keys from an array:

> {:a => 1, :c => 3, :d => 4}.keys & [:a, :d, :e]
 => [:a, :d] 

and if you want a boolean (following Andrew's suggestion):

> ({:a => 1, :c => 3, :d => 4}.keys & [:a, :d, :e]).empty?
 => false 
> ({:a => 1, :c => 3, :d => 4}.keys & [:f, :e]).empty?
 => true 

Solution 2

I would do something like this:

[:a, :b, :e].any?{ |val| h.key?(val) } 

Solution 3

h.select{|k| [:b, :w, :e].include?(k) }.empty?
h.select{|k| [:a, :w, :e].include?(k) }.empty?

And you get hash (key and value) of matching key in return (without empty?)

Share:
13,031

Related videos on Youtube

jrichardlai
Author by

jrichardlai

Currently a student in my senior year at SUPINFO, a French computer science school located in San Francisco. I am looking for an internship as Ruby On Rails developer starting from April 2011. If you have any available position, please contact me.

Updated on May 31, 2022

Comments

  • jrichardlai
    jrichardlai about 2 years

    Do you know a pretty ruby way to find if an hash has one of some keys ?

    h = {:a => 1, :c => 3, :d => 4}
    # keys to find are :a, :b or :e
    

    I know that I can do a :

    h.key?(:a) || h.key?(:b) || h.key?(:e)
    

    But I was wondering if there was a prettier way to do it ! :)

    Thanks a lot !

  • Admin
    Admin about 13 years
    +1 Nice "alternative" solution with a set intersection. I would add that length > 0 of the result implied existence of at least one key.
  • oligan
    oligan about 13 years
    @pst: You could use .empty? if you just wanted a boolean.
  • famousgarkin
    famousgarkin almost 10 years
    Or .any? to check the opposite.
  • poorva
    poorva almost 10 years
    .keys converts symbolic keys into strings, so it should be check like - {:a => 1, :c => 3, :d => 4}.keys & ['a', 'd', 'e'].