'Returning to main function on Ruby?

I'm making a very simple code here to practice with Ruby and going to implement a simple "client, product, sell" interface

# Ohayou Sekai

num_clientes = 0
num_produtos = 0
num_vendas = 0
clientes = Array.new    #cria array de clientes
produtos = Array.new    #cria array de produtos
vendas = Array.new      #cria array de vendas

print "1 - Client
    2 - Product
    3 - Sale
    0 - Close program
    insert the manipulation code desired: ";
    end

init = gets.chomp
cont1 = "1"

while init != "0"
  
    ##### client manipulation #####
  
    while init == "1"
  
      puts "\n1 - Add client"
      puts "2 - Visualize registered clients"
      puts "3 - Edit client"
      puts "4 - Remove client"
      puts "0 - Return to previous menu"
      print "\nInsert the desired option: "
      cont1 = gets.chomp 

Now the problem is: I'm entering good at the first while, but once in it, I'm struggling to return to the previous menu when the input for "cont1" is equal to 0

any idea of what I can do here ?



Solution 1:[1]

It seems like you are not clear on when to use an if statement and when to use a while loop. Your code is also has lots of misplaced or missing end keywords, so it wouldn't even run at all. I fixed all of that and made something that works:

@clientes = []
@produtos = []
@vendas = []

def client_manipulation
  while true
    print <<END
1 - Add client
2 - Visualize registered clients
3 - Edit client
4 - Remove client
0 - Return to previous menu
Insert the desired option:
END
    choice = gets.chomp
    return if choice == "0"
  end
end

while true
  print <<END
1 - Client
2 - Product
3 - Sale
0 - Close program
Insert the manipulation code desired:
END
  choice = gets.chomp
  client_manipulation if choice == "1"
  break if choice == "0"
end

I made your arrays at the top be instance variables so you can access them in multiple functions. I also removed the variables like @num_clientes because you should just do @clientes.size if you need to get the number of clients.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Grayson