Меню опций в Ruby - PullRequest
       1

Меню опций в Ruby

5 голосов
/ 10 марта 2011

Я пытаюсь создать меню в 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

Я также хотел бы иметь возможность после вызова класса вернуться к классу Options. Я уверен, что это легко, но я не могу решить это.

Спасибо еще раз,

Росс.

Ответы [ 3 ]

12 голосов
/ 10 марта 2011

Вы можете проверить 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
1 голос
/ 10 марта 2011

Я собирался дать вам всего несколько советов, но ваш код делает несколько неправильных вещей:

  1. Отступы - сделайте ваш код читабельным!
  2. Код в телах классов действителен в ruby, но это не делает его хорошей идеей - его основное использование - для метапрограммирования.
  3. Не вводить пользовательский ввод в константы. Это не так.

Так как бы я это закодировал? Примерно так:

class App

  def initialize
    main_menu
  end

  def navigate_to(what)
    what.new.display
    main_menu
  end

  def main_menu
    puts "Please select 1 for Acceleration and 2 for Energy."
    case gets.strip
    when "1"
      navigate_to AccelCalc
    when "2"
      navigate_to EnergyCalc
    else
      puts "Choose either 1 or 2."
      main_menu
    end
  end
end

class AccelCalc
  include Physics
  def display
    puts "Please enter the mass of the object"
    @m = gets.to_f
    puts "The mass of the object is #{@m}."
    puts "Please enter the speed of the defined object."
    @s = gets.to_f
    puts "The speed of the object is set at #{@s}."
    puts "The acceleration will now be calculated."
    puts @s * @m
  end
end

# ...

App.new    # Run teh codez
1 голос
/ 10 марта 2011

Хотя я на самом деле не получаю то, что нужно, одна вещь, которая сразу бросилась мне в глаза, это блок:

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

gets возвращает строку.Поэтому вы должны сделать:

case gets().strip()
when "1"
  puts "AccelCalc"
when "2"
  puts "EnergyCalc"
else
  puts "Invalid input."
end

Я использовал здесь явные скобки, вместо gets().strip() вы можете просто написать gets.strip в Ruby.Это выражение читает что-то из стандартного ввода и удаляет все пробелы вокруг него (новая строка после нажатия клавиши ввода).Затем полученная строка сравнивается.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...