Search code examples
rubyarrayspromptgets

Ruby "gets" prompts user for input. How do I get input (string) to reference existing object?


I'm prompting the user with gets to give me either peg1, peg2, or peg3, which each reference an array already made before the prompt. However, the input from the user is a string, which would be "peg1", "peg2", or "peg3". How do I make the user's input actually reference/attach to my 3 arrays that are already made?


Solution

  • If you assign all the possible arrays to a Hash keyed by the name of the array, you can simply ask the user for that name and then select the array from the hash. Using this technique, you don;t need to hardcode your values into a long case statement or (even worse) eval anything.

    def ask_for_peg(pegs)
      peg = nil
      while peg.nil?
        print("Which peg do you want? ")
        id = gets.strip
        peg = pegs[id]
      end
      peg
    end
    
    available_pegs = {
      "peg1" => array_for_peg1,
      "peg2" => array_for_peg2,
      "peg3" => array_for_peg3
    }
    
    selected_peg = ask_for_peg(available_pegs)
    # results in one of the arrays assigned in the available_pegs array above