Home > database >  How to implement an object in Ruby with regex
How to implement an object in Ruby with regex

Time:06-30

Absolute beginner in Ruby.

I need to create a class that contains the following keys:

Dict API that I need to follow

I know that this might be the structure, but can anybody help me with syntax?

class PixKey
def cpf
    ^[0-9]{11}$
end
def cnpj
    ^[0-9]{14}$
end
def phone
    ^\ [1-9][0-9]\d{1,14}$
end
def email
    ^[a-z0-9.!#$&'* \/=?^_`{
end
def evp
    [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
end

end

CodePudding user response:

To return the regular expressions for further use, you could return the regex using /:

class PixKey
  def cpf
      /^[0-9]{11}$/
  end
end

You could run PixKey.new.cpf to return the regex:

irb(main):022:0> PixKey.new.cpf
=> /^[0-9]{11}$/

You could also make it a class method by putting self. in front of the method name or add the line class << self as the first line in your class to make them all class methods by default (don't forget the end in this case).

class PixKey
  def self.cpf
      /^[0-9]{11}$/
  end
end
class PixKey
  class << self
    def cpf
      /^[0-9]{11}$/
    end
  end
end

With this you could run PixKey.cpf to return the regex:

irb(main):022:0> PixKey.cpf
=> /^[0-9]{11}$/

CodePudding user response:

You can define regular expressions using the /.../ regular expression literal.

Since regular expressions are immutable, I would simply use constants:

class PixKey
  CPF = /^[0-9]{11}$/
  CNPJ = /^[0-9]{14}$/
  PHONE = /^\ [1-9][0-9]\d{1,14}$/
  EMAIL = /^[a-zA-Z0-9.!#$%&'* \/=?^_`{|}~-] @[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
  EVP = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
end

In the above, I've changed the email regexp to the one suggested by the HTML standard because the one in your screenshot was probably destroyed by a markdown parser.

You can use the above like this:

PixKey::CPF.match?('12345678901')        #=> true
PixKey::CNPJ.match?('12345678901234')    #=> true
PixKey::PHONE.match?(' 5510998765432')   #=> true
PixKey::EMAIL.match?('[email protected]')   #=> true
PixKey::EVP.match?('123e4567-e89b-12d3-a456-426655440000') #=> true

Of course, you're not limited to match?, you can use any method from the Regexp class or pattern matching methods from String.

Note that in Ruby, ^ and $ match beginning and end of line which can cause problems in multi-line strings:

string = "before
 5510998765432
after"

string.match?(PixKey::PHONE) #=> true

If you want to match beginning and end of string (i.e. only match whole strings), you can use \A and \z instead:

PixKey::PHONE = /\A\ [1-9][0-9]\d{1,14}\z/

string.match?(PixKey::PHONE) #=> false

string = ' 5510998765432'

string.match?(PixKey::PHONE) #=> true
  • Related