Building expressions in strings

Hi list,

In my program I need to combine together two Ruby expressions with
a binary operator or apply an unary one on an expression. The
expressions
are given in strings and the returned expression is a String too.

def binary(exp1, op, exp2)
if %i[ + - * ** & | && || ].member? op
“(#{exp1}) #{op} (#{exp2})” # infix format
else
“(#{exp1}).#{op}(#{exp2})” # method call format
end
end

I would like to know if there’s a simple way to eliminate the safety
parentheses
if they are not necessary. binary(“1 + 1”, :*, “2 + 2”) needs the
parentheses, but
binary(“1 + 1”, :+, “2 + 2”) doesn’t.

Can Ripper or any additional gem elevate the main operator (I mean the
operator that would
be evaluated lastly) in an expression to make it possible to check
precedence?

How do I know if I really need the parentheses before the . in the
method
call format line?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs