TheLinuxGuy
TheLinuxGuy

Reputation: 27

How to build a simple menu-based console application?

It's been a week since I am learning Ruby. It's an awesome language and I am enjoying it.
I am still a noob. Here's a question:

I want a Console Application in Ruby to ask users to hit Num-Keys to choose options like a program with five functions. First four functions for SUM, SUB, MUL and DIV and last one is for returning to main menu.

I tried to write code but I failed. Here is the code:

puts "Choose Option(Press the num key)\n
  1. For SUM\n
  2. For SUB\n
  3. For MUL\n
  4. For DIV\n
  5. For Main Menu"

$x = 22
$y = 32

def gloabl_f(n) # <= global function start here

  def sum(x,y) # <= SUM function
    return x+y
  end

  def sub(x,y) # <= SUB function
    return x-y
  end

  def mul(x,y) # <= MUL function
    return x*y
  end 

  def div(x,y) # <= DIV function
    return x/y
  end

  def Main_Menu()
    return  puts "Choose Option(Press the num key)\n
  1. For SUM\n
  2. For SUB\n
  3. For MUL\n
  4. For DIV\n
  5. For Main Menu"
  end

  n = gets.to_i
  if n == 1
    puts sum(22,32)
  end
end # <= global function end here

Basically, I want the user to input two numbers first, and then to be able to choose an option of 1,2,3,4,5 by hitting the numeric keys related to above functions.

Upvotes: 0

Views: 1482

Answers (2)

Jesper
Jesper

Reputation: 4555

Some general points

  • It isn't very idiomatic to define methods inside of functions
  • You're never calling neither gloabl_f nor Main_Menu, you just define them.

Here's a sample solution:

def get_numbers
  puts "First number:"
  x = gets.chomp.to_i
  puts "Second number:"
  y = gets.chomp.to_i
  yield(x,y)
end

def sum(x,y)
  x + y
end

puts "Choose Option:
1. For SUM
2. For SUB
3. For MUL
4. For DIV
5. Exit
"

n = gets.chomp.to_i

case n
  when 1
    get_numbers do |x,y|
      puts "Sum: #{sum(x,y)}"
    end
  when 2
    # code
  when 3
    # code
  when 4
    # code
  else 
    puts "Exiting"
end

I left the other options for you to implement.

Upvotes: 3

Yahor Zhylinski
Yahor Zhylinski

Reputation: 513

puts "Choose Option(Press the num key)\n
1. For SUM\n
2. For SUB\n
3. For MUL\n
4. For DIV\n
5. For Main Menu"
x = 22
y = 32

n = gets.chomp.to_i
if n == 1
    puts x + y
end

Upvotes: 0

Related Questions