Home > Net >  how to check if an argument is an integer and if not return nil
how to check if an argument is an integer and if not return nil

Time:03-11

how would I write this in ruby " check if something is an integer, if not return nil. otherwise divide it by 2 and return the result. I don't understand how to get it to check if it's not an integer and return nil. to write it in a function
def halve(x) x / 2 end

CodePudding user response:

In Ruby, you can use instance_of? to check if the object is an instance of a given class and is_a? which returns true if the given class is the class of the object, or if the given class is one of the superclasses of the object.

In Ruby polymorphism or duck-typing is preferred, in this example, I would argue that one of those methods is a great choice too. IMHO is_a? is more idiomatic than instance_of? in Ruby but that depends on your specific use case.

def halve(x)
  if x.is_a?(Integer)
    x / 2.0  
  else
    nil
  end
end

Note that I change x / 2 to x / 2.0 because imagine x = 3 then x / 2 would return 1 but x / 2.0 will return 1.5. See the docs of Integer#/ for details.

CodePudding user response:

def halve(x)
  x.is_a?(Integer) ? x.fdiv(2) : nil
end

#is_a?(obj) returns true if the argument passed is the class of that object. You can also use #kind_of?(obj).

#fdiv(n) returns float. 1.fdiv(2) will return 0.5 (might be what you want) unlike 1 / 2 which returns 0.

  • Related