这是我目前的计算器代码,但我不知道如何使这两个数字执行操作。
#calculator
#ask the user for the first number
puts "Please select your first number"
#store num_1 inside a variable
num_1 = gets.chomp.to_i
#spit back the number
puts "#{num_1}"
#ask the user what order of operation they want to use
puts "would you like to add, subtract, multiply, or divide this number?"
#store the order of operation inside a variable
operation = gets.chomp.to_i
#ask the user for a second number
puts "please select a second number to #{operation}"
#store num_2 inside a variable
num_2 = gets.chomp.to_i
#perform the task and spit out a number
answer = num_1 operation num_2
#spit out the number
puts "your answer for #{num_1} #{operation} #{num_2} = #{answer}"
答案 0 :(得分:2)
你几乎就在那里。在您的情况下,您需要调用public_send
方法来执行所需的操作。
answer = num_1.public_send operation, num_2
注意:operation = gets.chomp.to_i
应为operation = gets.chomp
。
根据您的代码,加法,减法,乘法或除法分别为+
,-
,*
和/
。现在,当您使用gest
方法将其作为输入时,您将在 chomping 之后获得'+'
,'-'
等。现在,如果您根据文档在String#to_i
,"+"
等上调用"-"
方法,
如果
str
开头没有有效号码,则会返回0
。
了解public_send
。