Can I dynamically call a math operator in Ruby?

后端 未结 2 411
鱼传尺愫
鱼传尺愫 2020-12-04 01:52

Is there something like this in ruby?

send(+, 1, 2)

I want to make this piece of code seem less redundant

if op == \"+\"
           


        
2条回答
  •  -上瘾入骨i
    2020-12-04 02:35

    As an other option, if your operator and operands happen to be in string format, say from a gets method, you can also use eval:

    For example:

    a = '1'; b = '2'; o = '+'

    eval a+o+b

    becomes

    eval '1+2'

    which returns 3

提交回复
热议问题