PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] how to check if an argument is an integer and if not return nil

 July 20, 2022     integer, methods, null, ruby     No comments   

Issue

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


Solution

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.



Answered By - spickermann
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing