如果else语句ruby,无法到达方法

时间:2017-03-10 02:21:33

标签: ruby

我目前正致力于构建猜词游戏。有一个单词,用户会猜到单词中的一个字符。如果用户猜测的角色实际上是在单词中,那么将给出反馈。例如,单词是" cookie"并且用户输入" o"那么反馈就是

_ o o _ _ _

在这种情况下,尝试次数等于单词的长度6.如果用户猜测不是单词的一部分的字符,例如" z"消息将显示错误。但是,我在访问if和else语句时遇到问题,它们仅适用于第一个输入。这是我的代码:



class Game
  attr_reader :word
  attr_accessor :guess_counts, :guesses, :user_input, :guess_array 

  def initialize(word)
    @word = word
    @guesses = ""
  end

  def tries
    @tries = @word.length
  end

  def guesses(user_input)
    @user_input = user_input
    @guesses << @user_input
  end

  def underscored
   return @word.tr('^' + @guesses, '_').chars.join(' ')
  end

 
  
end


# user interface

puts "Please enter a word to initialize the Guessing The Word game"
  secret_word = gets.chomp

  game = Game.new(secret_word)

puts "you have #{game.tries} attemps left"


guesses = []
tries = secret_word.length

while tries > 0 
  puts "Plese enter a letter you believe is in the secret word"
  letter = gets.chomp
    game.guesses(letter)
    
    guesses << letter 
    guess = guesses[0]
    
    
    if !secret_word.include? guess 
      puts "Letter not in word"
      tries -= 1 
      puts "you have #{tries} left "
      next
    elsif secret_word.include? guess
      p game.underscored
    else 
      puts "you lost"
    end
 end
&#13;
&#13;
&#13;

enter image description here

当我输入&#34; o&#34;时,您会在此图片中看到

它说的不是字母,而是如果我从字母开始&#34; o&#34;它会显示出来 enter image description here

1 个答案:

答案 0 :(得分:1)

问题是你写的时候总是抓住guesses数组中的第一个元素:

guess = guesses[0]

所以表达式!secret_word.include? guess是:

    当第一个猜测正确时,
  • 总是true,然后是
  • 第一个答案不正确时始终false

要解决此问题,您可能需要抓住最后一个猜测;即

guess = guesses.last 

# `.last` is convenience method for accessing last element of an array; like so
#
#     guess = guesses[-1]

letter声明的当前if:即

if !secret_word.include? letter
  # [...]
elsif secret_word.include? letter
  # [...]