我试图在Ruby中创建一个菜单,以便根据用户输入的内容,取决于调用哪个类.然后在这种情况下,它将返回"Main"或类"Options".
我希望有一个人可以帮助我.这是我的代码.
module Physics
G = 21
C = 20000
Pi = 3.14
D = 100
end
class Options
puts "Please select 1 for Acceleration and 2 for Energy."
option = gets()
if option == 1
then
puts "AccelCalc" # This is the bit that needs to direct the user to the class AccelCalc
else
puts "EnergyCalc" # This needs to take them to EnergyCalc.
end
end
class AccelCalc
include Physics
puts "Please enter the mass of the object"
M = gets()
puts "The mass of the object is " + M + "."
puts "Please enter the speed of the defined object."
S = gets()
puts "The speed of the object is set at " + S + "."
puts "The acceleration will now be calculated."
puts S.to_i*M.to_i
end
class EnergyCalc
include Physics
puts "This will use the function E=MC^2 to calculate the Energy."
puts "Enter object mass"
M = gets()
puts "The mass is " + M + "."
puts "Now calculating the Energy of the object."
puts M.to_i*C_to.i**2
end
$end
Run Code Online (Sandbox Code Playgroud)
我也希望能够在课程被调用后返回clas选项.我确信这很容易,但我无法解决.
再次感谢你,
罗斯.
Jon*_*röm 12
你可以查看Highline.这是一个用于创建控制台应用程序的简单框架.安装它
sudo gem install --no-rdoc --no-ri highline
这是一个例子.
require "rubygems"
require "highline/import"
@C = 299792458
def accel_calc
mass = ask("Mass? ", Float)
speed = ask("Speed? ", Float)
puts
puts("mass * speed = #{mass*speed}")
puts
end
def energy_calc
mass = ask("Mass? ", Float)
puts
puts("E=MC^2 gives #{mass*@C**2}")
puts
end
begin
puts
loop do
choose do |menu|
menu.prompt = "Please select calculation "
menu.choice(:Acceleration) { accel_calc() }
menu.choice(:Energy) { energy_calc() }
menu.choice(:Quit, "Exit program.") { exit }
end
end
end
Run Code Online (Sandbox Code Playgroud)
虽然我并没有真正明白这里想要什么,但立即跳入我眼帘的一件事是这个块:
option = gets()
if option == 1
then
puts "AccelCalc" # This is the bit that needs to direct the user to the class AccelCalc
else
puts "EnergyCalc" # This needs to take them to EnergyCalc.
end
Run Code Online (Sandbox Code Playgroud)
gets返回一个字符串。所以你应该这样做:
case gets().strip()
when "1"
puts "AccelCalc"
when "2"
puts "EnergyCalc"
else
puts "Invalid input."
end
Run Code Online (Sandbox Code Playgroud)
我在这里使用了显式括号,而不是gets().strip()您可以简单地用 Ruby 编写gets.strip。这个表达式的作用是从标准输入中读取一些内容并删除它周围的所有空格(按回车键换行)。然后比较结果字符串。