Ruby 获取一个运算符并使其作为一个运算符工作

Ruby Get a operator and make it work as one

菜鸟到极点了。

如何让这个运算符工作?

puts "Tell me a number"
num1 = gets
puts "Tell me an another number"
num2 = gets
puts "Tell me an operator"
op = gets

puts num1.to_i op num2.to_i

在 Ruby 中,运算符基本上是一种方法。这样做:

puts num1.to_i.public_send(op.chomp, num2.to_i)

使用 Object#public_send,您可以发送使用字符串或符号指定的 (public) 方法。 请注意,如果您的 Ruby 版本较旧,您可能需要将 public_send 替换为 send

正如您在其他答案中看到的那样,您可以使用 send(或 public_send)来调用方法。

存在一个问题:gets 包含换行符(例如 +\n)。 to_i 方法可以处理这个问题。 send 尝试使用换行符查找方法(但找不到)。所以你必须从运算符中删除换行符(使用 strip-method.

所以完整的例子:

puts "Tell me a number"
num1 = gets
puts "Tell me an another number"
num2 = gets
puts "Tell me an operator"
op = gets

puts num1.to_i.send( op.strip,  num2.to_i)

我建议阅读后立即转换值,这样以后的生活会更轻松:

puts "Tell me a number"
num1 = gets.to_i
puts "Tell me an another number"
num2 = gets.to_i
puts "Tell me an operator"
op = gets.strip

puts num1.public_send( op,  num2)

请注意,不检查有效运算符。当你输入

1
2
u

您收到 undefined method 'u' for 1:Integer (NoMethodError)-错误。