How do you overload methods in Ruby?


#1

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
  end
end

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


FAQ: Ordering Your Library - Default Parameters
FAQ: Ordering Your Library - Default Parameters
#2

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.


#3

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?).


#4

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.


Edit

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