Ruby regex key search

前端 未结 4 1913
情书的邮戳
情书的邮戳 2021-02-04 13:28

http://ruby-doc.org/core-1.9.3/Hash.html#method-i-include-3F

It is possible to convert hash.has_key?(String) to have a regex search capabilities?

4条回答
  •  别那么骄傲
    2021-02-04 14:08

    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 
    

提交回复
热议问题