arrays - Ruby "gets" prompts user for input. How do I get input (string) to reference existing object? -
i'm prompting user gets give me either peg1, peg2, or peg3, each reference array made before prompt. however, input user string, "peg1", "peg2", or "peg3". how make user's input reference/attach 3 arrays made?
if assign possible arrays hash keyed name of array, can ask user name , select array hash. using technique, don;t need hardcode values long case
statement or (even worse) eval
anything.
def ask_for_peg(pegs) peg = nil while peg.nil? print("which peg 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 1 of arrays assigned in available_pegs array above
Comments
Post a Comment