How to call operator as function

Hi *,

could you help me please ? I’m trying to write a code where I could
have
operators’ functions as values of hash and executing them in way like
this
(formal code):

#=============================
operators = { “+” => Fixnum.+,
“-” => Fixnum.-,
“++” => Myclass.++}

op = “+”

result = operatorsop if left.class==Fixnum and
right.class==Fixnum
#============================

is it possible ? Thanks,

Cheers,

V.

On 2008.11.15., at 11:56, Vladimir F. wrote:

         "-" => Fixnum.-,
         "++" => Myclass.++}

op = “+”

result = operatorsop if left.class==Fixnum and
right.class==Fixnum
#============================

++ is not supported by Ruby :slight_smile:

I would do

1.send ‘+’.to_sym, 2

unless you want to use some esoteric operator mappings, you don’t need
the hash.
Fixnum.+ doesn’t make that much sense because of Ruby’s duck typing
(and why would you want to restrict yourself to work with just certain
objects?)

p.s.: dobre tu vidiet matfyzaka :slight_smile:

Cheers,
Peter


http://www.rubyrailways.com

2008/11/15 Vladimir F. [email protected]:

op = “+”

result = operatorsop if left.class==Fixnum and right.class==Fixnum
#============================

is it possible ? Thanks,

Use send, if all operators are binary:

left.send(:+, right)
left.send(:-, right)

etc.

Stefan

Vladimir F. wrote:

operators = { “+” => Fixnum.+,
“-” => Fixnum.-,

“+” => Fixnum.instance_method(:+),
“-” => Fixnum.instance_method(:-),

          "++" => Myclass.++}

There is no ++ operator in ruby and you can’t define one.

op = “+”

result = operatorsop if left.class==Fixnum and
right.class==Fixnum

result = operators[op].bind(left).call(right) if left.is_a?(Fixnum) and
right.is_a?(Fixnum)

Or you skip the whole thing with the hash and just do:

op = “+”
result = left.send(op, right)

HTH,
Sebastian

On Sat, Nov 15, 2008 at 08:07:17PM +0900, Sebastian H. wrote:

Vladimir F. wrote:

operators = { “+” => Fixnum.+,
“-” => Fixnum.-,

“+” => Fixnum.instance_method(:+),
“-” => Fixnum.instance_method(:-),

? ? ? ? ? ? ? “++” => Myclass.++}

There is no ++ operator in ruby and you can’t define one.

it’s Myclasses ++ operator

ICQ: 205544826

What I’m trying to do is Domain specific language class, for which I
could set
up names of variables, functions and operators and then parse and
execute
a string (f.e. “( a + ( b * c ) + sin ( d ) )”, where
variables could be hash { “a” => 1, “b” => 2, “c” => 3, “d” => 4} and
functions could be hash again so naturaly I asked whether it is possible
to
make it with operators). I tryied to use som ruby’s or irb’s native
DSL but withouth success.

V.

Vladimir F. wrote:

it’s Myclasses ++ operator

You can’t define ++ on any class. You just can’t. If the parser sees ++
anywhere it interprets it as two calls to +@ or one call to + and one to
+@.

HTH,
Sebastian