Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: What's the proper syntax for a boolean regex method?

Tags:

What is the proper syntax for a method that checks a string for a pattern, and returns true or false if the regex matches?

Basic idea:

def has_regex?(string)
    pattern = /something/i
    return string =~ pattern
end

Use case:

if has_regex?("something")
    # woohoo
else
    # nothing found: panic!
end
like image 253
Marco Avatar asked Feb 07 '10 00:02

Marco


People also ask

What does =~ mean in Ruby regex?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

How do you write regular expressions in Ruby?

Matches a whitespace character: /[ \t\r\n\f]/. Matches non-whitespace: /[^ \t\r\n\f]/. Matches a single word character: /[A-Za-z0-9_]/. Matches a non-word character: /[^A-Za-z0-9_]/.

What is a boolean in Ruby?

In Ruby, a boolean refers to a value of either true or false , both of which are defined as their very own data types. Every appearance, or instance, of true in a Ruby program is an instance of TrueClass , while every appearance of false is an instance of FalseClass .

What kind of regex does Ruby use?

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.


2 Answers

In the question you said:

... method that checks a string for a pattern, and returns true or false if the regex matches

As johannes pointed out String=~ returns nil if the pattern did not match and the position in the string where the matched word stared otherwise. Further he states in Ruby everything except nil and false behave like true. All of this is right.

However, they are not exactly true or false. Therefore, the last step is to coerce the value to be a Boolean. This is achieved by wrapping the result in double bangs returns a true.

def has_regex?(string)
    !!(string =~ /something/i)
end
like image 180
Ryan Avatar answered Sep 22 '22 02:09

Ryan


Your code looks fine, but you could write it even smaller.

The return value of String#=~ behaves this way:

  • nil if the pattern did not match
  • the position in the string where the matched word started

In Ruby everything except nil and false behaves like true in a conditional statement so you can just write

if string=~ pattern
  # do something
else
  # panic
end
like image 37
johannes Avatar answered Sep 22 '22 02:09

johannes