Roelof W. wrote in post #1149758:

Hello,

So I thought maybe a stack could solve this

So first I can convert one.add.one to 1+1 and that one can be solved by

using eval

Is this a good way to solve it.

Roelof

You can do it without explicit stack :use call stack…

====================================

class Op

attr_accessor :op,:fv,:lv

def initialize(op,firstValue)

self.op,self.fv,self.lv=op,firstValue,nil

end

def self.calculate(calc=false,&b)

a=Op.new(:+,0)

a.instance_eval(&b)

calc ? eval(a.string) : a.string

end

def self.tst_error &b

Op.calculate(true,&b) rescue puts “Ok, error detected: #{$!}”

raise “error not detected!”

end

def operande(n)

if self.lv==nil

raise “double operande” if self.op==:num

self.lv=Op.new(:num,n)

else

raise “double operande”

end

end

def operator(ope)

if self.op==:num

self.op=ope

self

else

raise “double operator”

end

end

def string()

return(self.fv.to_s) unless self.lv && self.op!=:num

if self.fv==0 && self.op==:+

“#{self.lv.respond_to?(:string) ? self.lv.string() : self.lv}”

else

“#{self.fv} #{op} #{self.lv.respond_to?(:string) ?

self.lv.string() : self.lv}”

end

end

def one() operande(1) end

def two() operande(2) end

def par(&b) operande(’(’+Op.calculate(false,&b)+’)’) end

0.upto(1000) {|v| define_method(“i#{v}”) { operande(v) } }

def add() operator(:+) end

def sub() operator( end

def mult() operator(:*) end

def div() operator(:/) end

end

# p Op.calculate { one }

p Op.calculate { one.add }

p Op.calculate { one.add.one }

p Op.calculate { one.add.i100.sub.one}

p Op.calculate { two.mult.par { one.add.i100 } }

p Op.calculate { two.mult.par { one.add.i100 }.add.one }

p Op.tst_error { one.add.add.one }

ruby essai2.RB

“1”

“1”

“1 + 1”

“1 + 100 - 1”

“2 * (1 + 100)”

“2 * (1 + 100) + 1”

Ok, error detected: double operator