Ruby regex key search

I think that using any? is a good solution as stated by qqbenq, but I would prefer using it with grep since it's more succinct.

hash.keys.grep(/regexp/).any?

I would advise extending Hash with a new method instead of replacing has_key?.

class Hash
  def has_rkey?(search)
    search = Regexp.new(search.to_s) unless search.is_a?(Regexp)
    !!keys.detect{ |key| key =~ search }
  end
end

This will work with strings, symbols or a regexp as arguments.

irb> h = {:test => 1}
 => {:test=>1}  
irb> h.has_rkey?(:te)
 => true 
irb> h.has_rkey?("te")
 => true 
irb> h.has_rkey?(/te/)
 => true 
irb> h.has_rkey?("foo")
 => false 
irb> h.has_rkey?(:foo)
 => false 
irb> h.has_rkey?(/foo/)
 => false 

Tags:

Ruby

Hashmap