Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex key search

Tags:

hashmap

ruby

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?

like image 770
Mr. Demetrius Michael Avatar asked Aug 16 '12 16:08

Mr. Demetrius Michael


People also ask

How regex works in ruby?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.

How do you match a string in Ruby?

Ruby | Regexp match() functionRegexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search. Return: regular expression with the string after matching it.

What method should you use when you want to get all sequences matching a regex pattern in a string?

To find all the matching strings, use String's scan method.


2 Answers

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 
like image 76
Kyle Avatar answered Nov 15 '22 21:11

Kyle


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?
like image 43
Adam Avatar answered Nov 15 '22 22:11

Adam