【问题标题】:How to get a string when using gets method in ruby在ruby中使用gets方法时如何获取字符串
【发布时间】:2014-03-29 23:44:36
【问题描述】:

我正在用 Ruby 制作一个简单的基于文本的井字游戏。我的游戏将首先询问用户他们想要成为 X 还是 O。我使用变量 userSym 来存储用户输入。根据文档,gets 返回 Nil 或 String (Kernel class)。我的代码行为不正常,因为 userSym 变量不是字符串,我不知道为什么。有什么我想念的吗?任何帮助表示赞赏!

puts "Welcome to TicTacRuby!"
puts "Please select your symbol. X goes first, O goes second. "

userSym = ''
begin
    userSym = Kernel.gets.match(/XO/)
rescue
    puts "Invalid input! Please enter X or O: "
else
    userSym.to_s
end

puts userSym.class
puts userSym
userSym == "X" ? first = 1 : first = 0

if first then 
    puts "You will play as #{userSym}, you will play first."
else
    puts "You will play as #{userSym}, you will play second."
end 

pamcakes-1015E:~$ ruby tictactoe.rb 
Welcome to TicTacRuby!
Please select your symbol. X goes first, O goes second. 
X
NilClass

You will play as , you will play first.

【问题讨论】:

  • /XO/ 更改为/[XO]/。这不会完全解决您的问题,但会引导您朝着正确的方向前进,因为您会看到该行返回一个 MatchData 对象而不是 nil

标签: ruby


【解决方案1】:

根据文档,String.match 返回 nil,或 match data

userSym.to_s 返回一个将被忽略的字符串,因此该行不会有任何可见的副作用。

【讨论】:

  • 糟糕,我以为我错过了一些愚蠢的东西。我将改为:userSym = gets.chomp userSym.match(/[XO]/) 非常感谢您的快速回复!
【解决方案2】:

使用begin ... rescue ... end 块来检查用户输入的是 O 还是 X 很麻烦。就这样做

input = gets.strip # strip removes newline
while input !~ /^(X|O)$/
  print "Invalid input! Please enter X or O: "
  input = gets.strip
end
p input
# => "X" or "O"

【讨论】:

    【解决方案3】:

    userSym = Kernel.gets.match(/X|O/) 有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2016-01-24
      • 1970-01-01
      • 2014-02-23
      相关资源
      最近更新 更多