开发者

Trying to go to a certain step after its completed one in ruby

Alright. I want it so the following would happen, Heres a sample:

puts "what would you like to see?"
var = gets.chomp
if var == "z"
  puts "this"

elsif var == "d"
  puts "stack"

elsif var == "y"
  puts "overflow"

else
  puts "I don't understand that."

end

Currently it works fine up until I want to have the user redefine the 'var'. Currently all the loops just loop back the puts from the elsif - i want it to ask for the user input again, then print out the elsif to that. For example:

Use开发者_JS百科r types in y, the code would say overflow, then return to line 1. Any help would be awesome.


gets returns nil when there is no input, and since nil evaluates to false in a conditional, you can use gets in a loop like so

while var = gets
  var.chomp!
  if var == "z" # use == to test equality, not =
    # do stuff
  elsif var == "x"
    # do stuff
  ....
end # while

You might find this works better with a case statement:

while var = gets
  case var.chomp
  when "z"
    puts "this"
  when "d"
    puts "stack"
  when "y"
    puts "overflow"
  else
    puts "I don't understand that."
  end # case
end # while


You're using the assignment operator (=) where you mean to test equality (==), I think.

You could also use case, but here's a version with while and if

print "Gimme an answer ('q' to quit) >> "
response = gets.chomp

while response != 'q'
  if response == 'z'
    puts "this"
  elsif response == 'd'
    puts "stack"
  elsif response == 'y'
    puts "overflow"
  else
    puts "I don't understand that."
  end

  print "Gimme another answer ('q' to quit) >> "
  response = gets.chomp
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜