O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Starting Small

The most likely place that you’re going to use regular expressions in Rails is the validates_format_of method demonstrated in Chapter 7, which is shown here as Example C-1.

Example C-1. Validating data against regular expressions

# ensure secret contains at least one number
  validates_format_of :secret, :with => /[0-9]/,
    :message => "must contain at least one number"

# ensure secret contains at least one upper case
  validates_format_of :secret, :with => /[A-Z]/,
    :message => "must contain at least one upper case character"

# ensure secret contains at least one lower case
  validates_format_of :secret, :with => /[a-z]/,
    :message => "must contain at least one lower case character"

These samples all use regular expressions in their simplest typical use case: testing to see whether a string contains a pattern. Each of these will test :secret against the expression specified by :with. If the pattern in :with matches, then validation passes. If not, then validation fails and the :message will be returned. Removing the Rails trim, the first of these could be stated roughly in Ruby as:

if :secret =~ /[0-9]/
  #yes, it's there
else
  #no, it's not
end

The =~ is Ruby’s way of declaring that the test is going to compare the contents of the left operand against the regular expression on the right side. It doesn’t actually return true or false, though—it returns the numeric position at which the first match begins, if there is a match, and nil if there are none. You can treat it as a boolean ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required