Home If statement operator as a variable in ruby
Reply: 2

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#
Ursus Reply to 2017-11-14 10:08:40Z

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)

Tom Lord
3#
Tom Lord Reply to 2017-11-14 12:06:55Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.329401 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO