“Yvon Thoraval” yvon.thoravalNO-SPAM@free.fr schrieb im Newsbeitrag
news:1gaxy9g.jksiqedi2kw8N%yvon.thoravalNO-SPAM@free.fr…
i have a script written in javascript and want to translate it into ruby
(using JRuby) but i face with the error about nested method which used
ofently in javascript.
The script controls a “Calculator” which gui is written in xpml, an xml
wrapper of java-swing components see :
http://www.ultrid.com/index.php?module=Static_Docs&func=view&newlang=eng
then i wonder how to convert this, for example :
function doIt() {
if ( type.equals(“operand”) ) {
doOperand();
}
else {
doValue();
}
}
into a ruby script.
each calculator’s button as two fields associated with it a type (might
be operand (ie +, =, -, /, *…) or value (0…9) and a value .
obviously i’ve tried something like :
def doIt(type, value)
if type == “operand”
doOperand(type, value)
else
doValue(type, value)
end
end
A direct translaction would have been:
def doIt
if my_type == “operand”
doOperand
else
doValue
end
end
Note the usage of my_type because type is already defined for each Ruby
object. But read on.
what is the ruby way for such nested methods ?
First of all this doesn’t seem to be about nested methods (i.e. methods
defined in the body of other methods) but about invoking methods from other
methods but much more about dispatching according to certain criteria (the
object’s type in this case).
From what I see this looks like a typical case of method overloading, which
is one of the most important features in object oriented languages: Method
invocation is done depending on the type of instance at hand (this, btw, can
be done similarly in JavaScript):
class Operand
def doIt
# do operand stuff
end
end
class Value
def doIt
# do value stuff
end
end
Now you just do
something = Operand.new
something.doIt
something = Value.new
something.doIt
If Operator and Value have some behavior (i.e. methods) in common, you can
even use inheritance, i.e. stick all common methods into a base class and
have sub classes derive from it:
class Base
def some_common_method
# whatever
end
end
class Operand < Base
def doIt
# do operand stuff
end
end
class Value < Base
def doIt
# do value stuff
end
end
something = Operand.new
something.some_common_method
something.doIt
something = Value.new
something.some_common_method
something.doIt
Now, here’s how you can achieve something similar with JavaScript (no
inheritance in this example). Paste this into a .html file and see what
happens:
Test