到了极致。
怎样才能让这个接线员工作?
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发布于 2019-11-18 06:30:02
在Ruby中,运算符基本上是一种方法。这样做:
puts num1.to_i.public_send(op.chomp, num2.to_i)使用Object#public_send,可以发送使用字符串或符号指定的(public)方法。注意,如果您的Ruby是旧版本,您可能需要用public_send替换send。
发布于 2019-11-18 11:54:45
正如您在其他答案中所看到的,您可以使用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)-error。
https://stackoverflow.com/questions/58905279
复制相似问题