如何在Ruby中查找和匹配字符串中的唯一字母?

时间:2017-10-03 17:15:26

标签: ruby

我正在构建一个挂人应用游戏。这里,用户猜测“b”,“a”和“n”,这将导致获胜。 @word实例变量将随机提供一个单词,在本例中,它是“banana”。

@guesses = Array["b", "a", "n"]
@word = "banana"

这里我只允许@guesses中的唯一字母

如何知道@word中的所有唯一字母是否都在@guesses内?

有没有预先制定方法的方法?

以下是我的代码。我在最后一个方法中检查了胜利,def check_win_or_lose

class HangpersonGame

# add the necessary class methods, attributes, etc. here
# to make the tests in spec/hangperson_game_spec.rb pass.

# Get a word from remote "random word" service

# def initialize()
# end
attr_accessor :word, :guesses, :wrong_guesses
def initialize(word)
   @word = word
   @guesses = '';
   @wrong_guesses = '';
end


def guess(letter)
  # throws an error when letter is empty, not a letter, or nil
  if letter.nil? || letter.empty? || !(letter =~ /[[:alpha:]]/)
    raise ArgumentError
  end

  # make case insensitive
  letter.downcase!

  # check that the "letter" is not empty or null
  # also check if the letter is already in the guesses and wrong_guesses 
  # instance variable, if so then this is not a valid guess, 
  # return false, if not false then determine if it's a correct or wrong guess.
  if (@guesses.include?(letter)) || (@wrong_guesses.include?(letter))
    false
  else 
    if @word.include?(letter)
        @guesses << letter
    else 
        @wrong_guesses << letter
    end
  end
end #end of guess method


def word_with_guesses
  # if @guesses is emtpy, then display '------'
  # searched on google another way to repeatedly display strings 
  # because using while loop or any other loop gives an error.
  if guesses.empty?
    "-"*@word.size
  else
    # if @guesses isn't empty, then display to the user all the 
    # correctly guessed letters inside @guesses using .gsub
    @word.gsub(/[^#{@guesses}]/, "-")
  end
end # end of word_with_guesses method


def check_win_or_lose
  # check if it's a lose by checking if there are 7 letters in @wrong_guesses
  if @wrong_guesses.length == 7
    :lose
  # check if it's a win
  elsif ????????
    :win
  # else continue playing: no win or lose
  else 
    :play
  end
end


# You can test it by running $ bundle exec irb -I. -r app.rb
# And then in the irb: irb(main):001:0> HangpersonGame.get_random_word
#  => "cooking"   <-- some random word
def self.get_random_word
  require 'uri'
  require 'net/http'
  uri = URI('http://watchout4snakes.com/wo4snakes/Random/RandomWord')
  Net::HTTP.new('watchout4snakes.com').start { |http|
  return http.post(uri, "").body
  }
end

end

1 个答案:

答案 0 :(得分:0)

我会这样写:

@guesses = ["b", "a", "n"]
@word = "banana"

#All guesses in @word?:
p @guesses.all?{|char| @word.include?(char)} #=> true
# All characters in @word are in @guesses:
p @word.chars.uniq.all?{|char| @guesses.include?(char)} #=> true