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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

7 Comments

when integer params are passed i.e. "8" it returned false
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 ruby-doc.org/core-2.3.0/Kernel.html#method-i-Integer
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
I ignored the cop after this chat, seems appropriate
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.