Q:

use variable in if statement operator in ruby

I have a variable that contains either '&&' or '||' and I need to use it in an if statement like so.
operator = '&&'

result = 1===1 operator 2===2

#=> result = 1===1 && 2===2

How can I achieve this?
I have tried using #public_send but to no avail.
Any help would be appreciated.

A:

The && operator is more of a low-level syntax element than & and | which are method calls. That makes it harder to do.
However, there's two ways:
a = true
b = false
c = true

If you want && equivalence:
[ a, b, c ].all?
# => false
[ a, c ].all?
# => true

If you want || equivalence:
[ a, b, c ].any?
# => true
[ a, b ].any?
# => true
[ b ].any?
# => false

A:

You could do it like this:
operator = "&&"
result = eval "1===1 #{operator} 2===2"

does that do what you want?
or if 1===1 is just a placeholder here for some expression, assign the result to a variable, so:
operator = "&&"
a = 1===1
b = 2===2
result = eval "#{a} #{operator} #{b}"

(of course, as commenters have noted, you must pay attention to the security vulnerabilities of eval, e.g. check that the operator variable is either "&&" or "||".)
and if you really want an if statement:
if operator == '&&'
  1===1 && 2===2
elsif operator == '||'
  1===1 || 2===2
else
  # dunno
end

