user2448377
user2448377

Reputation: 69

Ruby, Within a While Loop, Convert String to Method Call

This is lives within a method "play" that is called once. After you enter the while loop, you stay there until you exit the process. Right now, I'm trying to use the case statement to turn user-defined strings into the variable that is passed at the end to call the next method, all within the while loop.

def play
  next_action = @start # comes from an initialize function earlier in script
  while true
    case next_action
    when beginning
      next_action = beginning
    when "instruct"
      next_action = instructions
    when "display"
      next_action = display_users
    else
      puts "Unknown command."
      next_action = display_users
    end
    puts "\n----------"
    next_action = method(next_action).call
  end
end

First problem: the case statement fails to recognize any choice but the last.

Second problem: this leads to the loop ending, jumping to the last method called, and then exiting the process.

Any help or advice is appreciated.

Upvotes: 1

Views: 262

Answers (2)

steenslag
steenslag

Reputation: 80065

See if changing

next_action = @start

to:

next_action = @start.chomp

gets you any further.

Upvotes: 1

Tilo
Tilo

Reputation: 33732

you should use a state-machine instead.

See: http://railscasts.com/episodes/392-a-tour-of-state-machines

Upvotes: 0

Related Questions