ekultek ekultek - 16 days ago 10
Ruby Question

Return user to where they came from

Is there a way you can return a user to where they came from without having to go deep into else if statements?

Such as, say they came from here:

def start
puts "Some code press 'E' to go to examples"
input = gets.chomp
if input =~ /e/i
examples
else
start
end
end


And they went to examples:

def examples
puts "Examples of code to return to where you came from type 'return'"
input = gets.chomp
if input == 'return'
#<= (return them to where they came from)


I know that in order to do this you call the method which would be
start
but I want them to return to where they came from no matter where they come from, be it
start, lesson_1, lesson_2, lesson_3
etc. Without having to make a ridiculous amount of if elsif else statements. Is there a way to do this without going super deep into if else statements?

Meaning;

if input == "y"
start
if input == "r"
return
if input == "w"
wait
else
return
end
else
start
end
else
return
end

Answer

The sort of thing you're describing is solved by a finite state machine.

Rather than having a big, complicated if/elsif block, you define states of your program and what states they can move into. You can draw this out like a flowchart.

  • Start the program -> start
  • start -> wait or start
  • wait -> quit or start
  • quit -> Exit the program

The FSM can be done as a class, each state is a method. The methods only need to know about their next steps.

Here's an article about state machines in Ruby and list of Ruby state machine libraries.