How do you overload methods in Ruby?

I have just a general question, dont know if this place is the right spot to ask, but i give it a try:
coming from java, its hard not to define variables in methods. Sometimes it is a pro and makes stuff easier, but at the same time i feel like loosing control over potential errors. In java you can overload methods, but how do you do that in ruby? Do i have to check the variable type of the input (how can i do that?) inside the method if i want to execute different code depending on the type of the input. Pseudocode example:

def my_method(input)
  if input.type=string 
    # do something with strings
  elsif input.type=integer
    # do something with integers
  elsif input.type=float
    # do something with floats

Looks kinda messy to me… Any suggestion or explenation is appreciated!

1 Like

In Ruby we use object.class to detemine which class the object belongs to…

input.is_a? (String)

We can also check if the object is an instance of a class…

input.instanceof? String

You will want to dig up all the documentation you can lay your hands on for quick reference as you find your bearings.


thanks a lot, helped me to fix my issue. Is there any difference in these two methods you mentioned? (i think in the second one you just forgot an underscore, it should be instance_of?).

1 Like

Thanks for noting that. I try to tax my memory rather than digging, sometimes. Oops.

Without really being sure, there is one distinction that stands out. I don’t think we can create our own data types, only objects. If we have a custom class, then is_a? might not be able to identify it. instance_of? will, though. Needs testing.

At any length there has to be something that one can do and the other not, else they are just convenient swaps of one another, which is not really a pattern we see inspite of the fact there are 100 ways to cook an egg in Ruby.


class A
  def aa
a =
puts a.instance_of? (A)    # true
puts a.is_a? (A)           # true
puts a.aa                  # AA