arrays - 如何替换字符串中的匹配字符?(红宝石)
问题描述
我正在构建一个刽子手游戏,但我不知道如何用 player_input(数组)中的匹配字母替换 hidden_word(字符串)中的下划线。有什么想法我应该做什么?提前谢谢你,我很感激!
def update
if @the_word.chars.any? do |letter|
@player_input.include?(letter.downcase)
end
puts "updated hidden word" #how to replace underscores?
end
puts @hidden_word
puts "You have #{@attempts_left-1} attempts left."
end
我有两个字符串 the_word 和 hidden_word 以及一个数组 player_input。每当玩家选择与 the_word 匹配的字母时,hidden_word 应该更新。
例如
the_word = "红宝石"
hidden_word = "_ _ _ _"
玩家选择“g”,hidden_word 仍然是“_ _ _ _”
玩家选择“r”,hidden_word 更新“R _ _ _”
这是其余的代码:
class Game
attr_reader :the_word
def initialize
@the_word = random_word.upcase
@player_input = Array.new
@attempts_left = 10
end
def random_word
@the_word = File.readlines("../5desk.txt").sample.strip()
end
def hide_the_word
@hidden_word = "_" * @the_word.size
puts "Can you find out this word? #{@hidden_word}"
puts "You have #{@attempts_left} attempts left."
puts @the_word #delete this
end
def update
if @the_word.chars.any? do |letter|
@player_input.include?(letter.downcase)
end
puts "updated hidden word" #how to replace underscores?
end
puts @hidden_word
puts "You have #{@attempts_left-1} attempts left."
end
def guess_a_letter
@player_input << gets.chomp
puts "All the letters you have guessed: #{@player_input}"
end
def has_won?
if !@hidden_word.include?("_") || @player_input.include?(@the_word.downcase)
puts "You won!"
elsif @attempts_left == 0
puts "You lost..."
end
end
def game_round #the loop need fixin
puts "Let's play hangman!"
hide_the_word
while @attempts_left > 0
guess_a_letter
update
@attempts_left -= 1 #fix this
has_won?
break if @player_input.include?("q") #delete this
end
end
end
new_game = Game.new
new_game.game_round
解决方案
这是一些可以帮助您前进的代码。将猜测的字母收集到一个数组中。然后,将单词的字符映射到猜到的字符或下划线。
word = "RHUBARB"
guessed_letters = ['A', 'R', 'U']
hidden_word = word.chars.map { |c| guessed_letters.include?(c) ? c : '_' }.join
# => "R_U_AR_"
推荐阅读
- java - 无法在 Cloudera VM 上使用 mvn 下载工件
- performance - 计算增量平均值/平均值是否有利于精度?
- java - 如何从 Spring Boot SimpleJdbcCall 对象中提取数据?
- android - Android:更改菜单项中的图标颜色
- ruby-on-rails - 如何在我的本地服务器 30000 上运行它?rails s 不工作
- powerbi - 过去 12 个月的 SUM 未在 powerBI 中正确计算
- java - 如何在 kotlin 中编写条件循环
- excel - Excel - 如何对连接的子字符串求和
- git - 当我没有进行任何更改时,Git (Gitkraken) 自发地显示更改的文件
- regex - 正则表达式匹配由空格转义双引号/单引号分割?