红宝石字符串运算符 [英] Ruby string to operator

查看:75
本文介绍了红宝石字符串运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组

operator = ['+', '-', '*', '/']

我想用它们以4种不同方式求解方程.我想这会是这样的:

And I want to use them to solve an equation in 4 different ways. I imagine it would be something like this:

operator.map {|o| 6 o.to_sym 3 } # => [9, 3, 18, 2]

我该怎么做?

推荐答案

使用

Do as below using Object#public_send method :

operator = ['+', '-', '*', '/']
operator.map {|o| 2.public_send o,2 }
# => [4, 0, 4, 1]

使用 Object#method

One more way using Object#method and Method#call:

operator = ['+', '-', '*', '/']
operator.map {|o| 2.method(o).(2) }
# => [4, 0, 4, 1]

这篇关于红宝石字符串运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆