user7055375
user7055375

Reputation:

How do I check if my hash has a key from an array of strings?

With Ruby, if I have a hash, what is the fastest way to check if it has a key from an array of strings? So I could do this

has_key = false
arr_of_strings.each do |str|
    if my_hash.has_key?(str)
        has_key = true
        break
    end
end

But taht seems like way too many lines of code for such a simple inquiry.

Upvotes: 0

Views: 583

Answers (3)

Mark Thomas
Mark Thomas

Reputation: 37517

To see if the array and the keys have any in common, you can use set intersection:

(arr & hash.keys).any?

Upvotes: 3

Josh Brody
Josh Brody

Reputation: 5363

strings = ['a', 'b', 'c']
hash = {:a => 'apple', :b => 'bob', :d => 'thing'}

has_key = hash.keys.map(&:to_s) & strings  # ['a', 'b']
has_key.any? # true

a one-liner that's similar, hash.keys.detect { |key| strings.include?(key.to_s) }.nil?

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

As simple as this:

arr_of_strings.any? {|s| my_hash.key?(s) }

Or, to get bonus points for clever-yet-less-readable code:

arr_of_strings.any?(&my_hash.method(:key?)) # => true

Upvotes: 5

Related Questions