首页 > 解决方案 > 如何替换字符串中的匹配字符?(红宝石)

问题描述

我正在构建一个刽子手游戏,但我不知道如何用 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

标签: arraysrubystringmethodsreplace

解决方案


这是一些可以帮助您前进的代码。将猜测的字母收集到一个数组中。然后,将单词的字符映射到猜到的字符或下划线。

word = "RHUBARB"
guessed_letters = ['A', 'R', 'U']
hidden_word = word.chars.map { |c| guessed_letters.include?(c) ? c : '_' }.join
# => "R_U_AR_"

推荐阅读