我正在学习使用 Ruby 构建hangman 应用程序的教程。它有一个隐藏单词的功能 masquerade,它只是从文件中导入的国家名称。问题是我不明白这实际上是如何掩盖这些词的,或者三元运算符是如何在注入中工作的。它正在检查字符是否为空白(即“”),如果是,则将其设置为空白(即“”),但如果不是,则将其设为 。该函数似乎没有处理单词具有实际字符(即字母)的事实。
谁能解释这种菜鸟,我误解了什么?另外,为什么它在最后(在结束之前)再次添加“伪装”?
def masquerade(word)
word.each_char.inject([]) { |disguise, char| disguise << (char == " " ? " " : " "); disguise }
end
游戏词举例
Afghanistan
Albania
Algeria
Andorra
Angola
Antigua & Deps
Argentina
Armenia
整个Word课
class Word
class << self
def get_random
content = File.read("countries.txt")
words = content.split("\n")
words[rand(words.size)].upcase
end
def masquerade(word)
word.each_char.inject([]) { |disguise, char| disguise << (char == " " ? " " : " "); disguise }
end
def reveal(last_revealed_word, char_clicked, final_word)
chars = final_word.each_char.to_a
last_revealed_word.each_index do |i|
last_revealed_word[i] = chars[i] if last_revealed_word[i] == " " and chars[i] == char_clicked
end
end
def chars_left(revealed_word)
revealed_word.count { |c| c == " " }
end
end
end