I';我是编程新手,想知道如何使用ruby创建计算器

I';我是编程新手,想知道如何使用ruby创建计算器,ruby,Ruby,这是我当前的计算器代码,但我不知道如何让这两个数字执行这个操作 #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 t

这是我当前的计算器代码,但我不知道如何让这两个数字执行这个操作

#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}"
answer = num_1.public_send operation, num_2

你快到了。在您的情况下,您需要调用
public\u send
方法来执行所需的操作

#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}"
answer = num_1.public_send operation, num_2
注意:
operation=gets.chomp.to_i
应该是
operation=gets.chomp

根据您的代码,加、减、乘或除将分别为
+
-
*
/
。现在,当您使用
gest
方法将这些作为输入时,您将在咀嚼后获得
'+'
'-'
等。现在,根据文档,如果对那些
“+”
“-”
等调用
String#to_i
方法

如果
str
开头没有有效数字,则返回
0

了解