Ruby正则表达式关键字搜索 [英] Ruby regex key search
本文介绍了Ruby正则表达式关键字搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
http:// ruby-doc。 org / core-1.9.3 / Hash.html#method-i-include-3F
可以将hash.has_key?(String)有一个正则表达式搜索功能?
解决方案
我会建议扩展 Hash
使用新方法而不是替换 has_key?
。
class Hash
def has_rkey?(搜索)
search = Regexp.new(search.to_s)除非search.is_a?(Regexp)
!! keys.detect {| key | key =〜search}
end
end
符号或正则表达式作为参数。
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 /)
=>假
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?
解决方案
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
这篇关于Ruby正则表达式关键字搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文