Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby implementation is_numeric? for Strings, need better alternatives

I wanted to validate 'numericality' of a string (its not an attribute in an active-record model). I just need it to be a valid base 10, positive integer string. I am doing this:

class String
  def numeric?
    # Check if every character is a digit
    !!self.match(/\A[0-9]+\Z/)
  end
end

class String
  def numeric?
    # Check is there is *any* non-numeric character
    !self.match(/[^0-9]/)
  end
end

Which of these is a more plausible alternative? OR, is there any other better implementation?

like image 612
Swanand Avatar asked Aug 17 '09 08:08

Swanand


2 Answers

Please make sure use \A and \Z rather than ^ and $, to match the entire string rather than just a single line in the string. If you want to avoid matching a string with an ending newline, use '\z' at the end. For more issues, see The Regex Tutorial on anchors.

For example, /^[0-9]+$/ successfully matches the following:

foo
1234
bar

but /\A[0-9]+\Z/ does not.

like image 177
Bkkbrad Avatar answered Sep 28 '22 07:09

Bkkbrad


The first one looks sane to me.

I'd name the method numeric?, though. I'm not a big fan of is_foo? methods. They make sense in languages that doesn't have question marks in method names (is_foo, isFoo), but with the question mark, the is feels redundant.

like image 26
August Lilleaas Avatar answered Sep 28 '22 07:09

August Lilleaas