0

I have found a code for checking whether string is numeric. And it works fine. But I am not getting how is it working. Can anyone explain it.

    str = "12132344", str1="abcd", str2="12213234.132332"

    /^[\d]+(\.[\d]+){0,1}$/ === str  #=> true  //perfect
    /^[\d]+(\.[\d]+){0,1}$/ === str1 #=> false //perfect
    /^[\d]+(\.[\d]+){0,1}$/ === str2 #=. true  //perfect

when i change the comparison like below:

    str === /^[\d]+(\.[\d]+){0,1}$/ #=>  false
    str1 === /^[\d]+(\.[\d]+){0,1}$/ #=> false
    str2 === /^[\d]+(\.[\d]+){0,1}$/ #=> false

Also I found alternate way to do this by using match.

Can anyone explain what is (===) operator doing here? How it works? Is there any other alternate way?

Rahul Tapali
  • 9,887
  • 7
  • 31
  • 44

2 Answers2

3

In Ruby, operator overloading can be used to define what each operator does, but it must be done by the class on the left hand side of the operator.

This method is defined in the Ruby Standard Library for the Regexp object class. Reference: http://www.ruby-doc.org/core-1.9.3/Regexp.html#method-i-3D-3D-3D.

It only works with the Regexp class (that is the pattern) on the left hand side because it is defined to work that way only in the Regexp class.

In this case, Regexp defines === as a synonym for =~, which matches a string given a regular expression pattern.

The String class defines the === operator as an equality operator. This means it returns false if the right hand argument is not a string, and otherwise returns true only if both strings match. Reference: http://www.ruby-doc.org/core-1.9.3/String.html#method-i-3D-3D-3D

ronalchn
  • 12,225
  • 10
  • 51
  • 61
1
def is_numeric?(str)
  str =~ /^[\d]+(\.[\d]+){0,1}$/
end
Erez Rabih
  • 15,562
  • 3
  • 47
  • 64