Home If statement operator as a variable in ruby

# If statement operator as a variable in ruby

Dheeraj Gupta
1#
Dheeraj Gupta Published in 2017-11-14 09:45:30Z
 I am trying to do something like this in ruby: x = 0 y = 1 z = "!=" if x #{z} y puts "True" end #True #=> nil x = 1 if x #{z} y puts "True" end #True #=> nil  Using a operator as a variable is not evaluating the expression. Any way to do this.
Ursus
2#
 Try this one x = 0 y = 1 z = "!=" x.public_send(z, y) => true  The trick here is know that 3 >= 5 is syntactic sugar for 3.>=(5)
 To reiterate the answer above, I'd suggest using send. However, it is possible to write the code in your original style - you just need to eval (i.e. execute) it: x = 0 y = 1 z = "!=" if eval("x #{z} y") puts "True" end  Generally speaking, the use of eval is strongly discouraged. It can lead to major security issues (e.g. if you're evaluating arbitrary user input!), and is quite a slow operation.