Michael Durrant
Michael Durrant

Reputation: 96454

How can I dynamcially use a parameter as an operator in Ruby?

I want to either add or subtract

so I pass in 'action' as a paramater

How do I do a 'action' b for a+b or a-b

I tried eval but no luck, undefined method 'action'

Upvotes: 0

Views: 36

Answers (2)

sawa
sawa

Reputation: 168071

Use send.

action = "+"
a.send(action, b)

Upvotes: 4

Raj
Raj

Reputation: 22926

Eval works for me.

2.0.0p247 :006 > action = '+'
 => "+"
2.0.0p247 :007 > eval("5 #{action} 2")
 => 7

Upvotes: 1

Related Questions