-1

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.

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35

2 Answers2

7

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)

Ursus
  • 29,643
  • 3
  • 33
  • 50
4

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.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77