Thursday, December 11, 2008

Ruby: How "send" method works?

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.
For example.
Suppose that in you have a three different parameter
1.addnum
2.subnum
3.multinum

depends on the parameter you want to call the method to execute add/subtract/multiply. So what you can do

class Number

def mainfunction(methodname, val1, val2)
#THE BELOW MENTION SEND METHOD WILL CALL ANY ONE METHOD #DEPENDS ON THE FIRST PARAMETER
self.send(methodname, val1, val2)
end

def addnum(val1, val2)
val1 + val2
end

def subnum(val1, val2)
val1 + val2
end

def multinum(val1, val2)
val1 + val2
end
end

num = Number.new
num.mainfunction(“addnum”, 10 , 20) #output => 30

So this is just a very basic example to understand hoe send method work.

No comments: