0

I tried rewriting this function numerous ways to get around this error, however, I want to defer to other experts before I disable the cop around it.

  def numeric?(obj)
    obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
  end

This is used like so:

  def index
    if params[:job_id] && numeric?(params[:job_id])

This issue was solved via: Checking if a variable is an integer

enter image description here

Update trying:

  def numeric?(string)
    !!Kernel.Float(string)
  rescue TypeError, ArgumentError
    false
  end

Reference How do I determine if a string is numeric?

New error: enter image description here

Community
  • 1
  • 1
Chris Hough
  • 3,389
  • 3
  • 41
  • 80

3 Answers3

1

The following code snippet does the trick:

def numeric?(arg)
  return false if arg.is_a?(Float)
  return !Integer(arg).nil? rescue false
end

Returns false for the following: 'a', 12.34, and '12.34'.

Returns true for the following: '1', 1.

Eli Foster
  • 68
  • 7
1
def numeric?(arg)
  !/\A[+-]?\d+\z/.match(arg.to_s).nil?
end

Passes all Rubocop tests from a default configuration. Complete gist with tests at https://gist.github.com/aarontc/d549ee4a82d21d263c9b

aarontc
  • 28
  • 4
0

You can write the method

def numeric?(obj)
  obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/).nil?
end

You really don't need to do nil comparisons and then based on the decision returning true/false. #nil? method does it for you.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • when integer params are passed i.e. "8" it returned false – Chris Hough Feb 19 '16 at 05:27
  • Ok, that is because of your regex. The answer was to address the rubocop error. To check the object is a Integer or not, you may try http://ruby-doc.org/core-2.3.0/Kernel.html#method-i-Integer – Arup Rakshit Feb 19 '16 at 05:28
  • well, the other answer does both, is there a way to incorporate both? I would prefer to use regex in this case, it seems much easier – Chris Hough Feb 19 '16 at 05:31
  • Why not try already attempted code ? http://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails :D http://stackoverflow.com/questions/26061584/how-do-i-determine-if-a-string-is-numeric – Arup Rakshit Feb 19 '16 at 05:33
  • the other one allows decimals... http://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails – Chris Hough Feb 19 '16 at 05:46
  • @chrishough I use double `!!` a lot. I don't know why it is a bad idea though. – Arup Rakshit Feb 19 '16 at 05:48
  • 1
    I ignored the cop after this chat, seems appropriate – Chris Hough Feb 19 '16 at 06:05