我建议不要使用数组,只使用字符串。
代码
def replace_underscores(word, hidden_word, guess)
word.scan(Regexp.new(guess)) { hidden_word[Regexp.last_match.begin(0)] = guess }
hidden_word
end
例子
word = "busboi"
hidden_word = "_" * word.length
replace_underscores(word, hidden_word, "a")
replace_underscores(word, hidden_word, "b")
replace_underscores(word, hidden_word, "r")
replace_underscores(word, hidden_word, "o")
replace_underscores(word, hidden_word, "u")
replace_underscores(word, hidden_word, "s")
检查是否已经猜出了hidden_word:
def guessed?(hidden_word)
hidden_word.count('_').zero?
end
guessed?(hidden_word)
Let's permit one more guess.
replace_underscores(word, hidden_word, "i")
guessed?(hidden_word)
注释
我使用了方法String#scan,并带有一个块,该块对每个匹配项执行。在块内,使用类方法Regexp::last_match检索MatchData对象。(或者,可以将全局变量$~
替换为Regexp.last_match
。有关详细信息,请搜索“special global variables” Regexp。)方法MatchData.begin用于获取要用猜测的字母替换的str
中字符的索引。
busboi
到底是什么?这是一个真实的单词吗? - Tom Lordbusboi
只是一个例子,@TomLord!哈哈 - Ed de Almeida