如何替换字符串中的匹配字符?(红宝石)



我正在构建一个刽子手游戏,我不知道如何将hidden_word(字符串(中的下划线替换为player_input(数组(中的匹配字母。任何想法我应该做什么?提前谢谢你,我很感激!

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 = "RUBY">

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_"

我不确定downcase,因为你也用过uppercase

仅选择一个字母大小写。

但它会为你工作:

def update
  @the_word.each_char.with_index do |letter, index|
     @hidden_word[index] = letter if @player_input.include?(letter.downcase)
  end
  puts @hidden_word
  puts "You have #{@attempts_left-1} attempts left."
end

它将每个秘密单词的字母与用户的输入进行比较,并且巧合地更改了隐藏单词中的下划线。

这里我用了String#each_charString#[]=Enumerator#with_index

一种选择是使用正则表达式:

@hidden_word = @the_word.gsub(/[^#{@player_input.join('')}s]/i, '_')

最新更新