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

StackOverflow https://stackoverflow.com/questions/16515179

  •  21-04-2022
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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

다른 팁

It's hard to understand what you're asking, but taking some guesses at what you mean, I think something like this shows you how to do what you want:

$peg1 = [:peg, :one]
$peg2 = [:peg, :two]
$peg3 = [:peg, :three]

def ask_which_peg
  print "Please choose peg1, peg2, or peg3: "
  case gets.chomp
  when "peg1"
    $peg1
  when "peg2"
    $peg2
  when "peg3"
    $peg3
  else
    nil
  end
end

peg = nil
until(peg)
  peg = ask_which_peg()
end

print peg, "\n"

The name of the array is for your benefit, but cannot be used in the actual program. So you cannot check if the input equals the name of a variable. However, you can easily check if the input equals "peg1", "peg2", or "peg3" using an if statement if input = peg1 and return the proper array in each case.

This will maybe do what you are asking.

peg1 = ['yellow']
peg2 = ['blue']
peg3 = ['green']
input = gets.chomp

input =~ /peg\d/ and
puts eval("#{input}")

This is sufficiently edited (from prior answer) to avoid eval of user input as a Ruby command. Will raise error on peg4 or other peg that doesn't exist.

The and flow control helps to check inputs.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top