سؤال

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'

هل كانت مفيدة؟

المحلول

Use send.

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

نصائح أخرى

Eval works for me.

2.0.0p247 :006 > action = '+'
 => "+"
2.0.0p247 :007 > eval("5 #{action} 2")
 => 7
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top