-1

I have a hash:

rule => {
  :quantity => 2,
  :operator => ">="
}

and

@quantity = 1

Using @quantity, rule[:operator], and rule[:quantity], I want to dynamically express:

if @quantity rule[:operator] rule[:quantity] # SyntaxError

such that it evaluates as:

if 1 >= 2

How can I do that?

user513951
  • 12,445
  • 7
  • 65
  • 82
Petros Kyriakou
  • 5,214
  • 4
  • 43
  • 82

2 Answers2

4

Operators in Ruby are "syntactic sugar" for methods.

a >= b

is equivalent to

a.>=(b)

Therefore, you can use send or public_send to dynamically call operators as methods.

op1 = '>='
op2 = '<'

1.send(op1, 2) # => false 
1.send(op2, 2) # => true

In your example, you'd use it like this:

if @quantity.send(rule[:operator], rule[:quantity])
user513951
  • 12,445
  • 7
  • 65
  • 82
3

Another way to do this would be to use the Method#method:

@quantity.method(rule[:operator])[rule[:quantity]]
Agis
  • 32,639
  • 3
  • 73
  • 81