timpone
timpone

Reputation: 19969

allow only integers to be input as an argument in Ruby

I need a Ruby script that accepts only integers in Ruby 2.1 and above (ie handle Bignum,Fixnum, and Integer).

I have:

  def push(val)
    return "only integers can be used" if !val.is_a?(Fixnum) || !val.is_a?(Integer)

but if I add Bignum, it doesn't seem to work. What would be the best way to do this? Or a different strategy?

Upvotes: 0

Views: 411

Answers (1)

mu is too short
mu is too short

Reputation: 434665

First of all, your logic is a bit backwards. You want to say:

return an error if val is not a Fixnum and not an Integer

That would be expressed as:

if !val.is_a?(Fixnum) && !val.is_a?(Integer)

If you add Bignum to that pattern then it'll work.

Secondly, Fixnum and Bignum have been deprecated in favor of just Integer as of (AFAIK) Ruby 2.4. Conveniently enough, both Fixnum < Integer and Bignum < Integer are true in Ruby 2.1 through 2.3 so there's no point to checking is_a? Fixnum, is_a? Integer, and is_a? Bignum, you could just check is_a? Integer since:

  1. As of Ruby 2.4, 10 and 10**100 are both Integers and Fixnum and Bignum are on the way out.
  2. In Ruby 2.1 to 2.3, both Fixnum (e.g. 11) and Bignum (e.g. 11*111) subclass Integer so 11.is_a? Integer and (11*111).is_a? Integer are true.
  3. Fixnum and Bignum went away completely in 2.4, now there is only Integer.

Simplify to:

return "only integers can be used" if !val.is_a?(Integer)

or perhaps:

return 'only integers can be used' unless val.is_a?(Integer)

or if you want to be a little looser and allow '23', use Kernel#Integer:

def push(val)
  val = Integer(val)
  #...
rescue ArgumentError, TypeError
  return 'only integers can be used'
end

or, depending on how much code you want the rescue to apply to:

def push(val)
  begin
    val = Integer(val)
  rescue ArgumentError, TypeError
    return 'only integers can be used'
  end
  #...
end

or perhaps:

def push(val)
  val = Integer(val) rescue nil
  return 'only integers can be used' if(val.nil?)
  #...
end

Upvotes: 1

Related Questions