2017-09-24 6 views
1

私はランダムに生成された単語の正しい位置にあると推測した文字の量を返すゲームを作ろうとしています(例えば、単語は "board"です。 "ボート"と入力すると2/5、ボードに入ると5/5になります)。ruby​​ return matching characater size

word = File.readlines("wordslist.txt").sample; 
guess = gets 
same = guess.each_char.zip(word.each_char).select{ |g,w| g == w }.size 

単語の長さの下にある任意の推測に対しては正常に動作します。単語が "bye"で、 "byk"と入力すると3/3が返されますが、 "by"を入力すると2/3が返されます。ただ私が何か悪いことをしているかどうかを調べるだけです。

答えて

1

これは、File.readlinesgetsの両方が、返された文字列の末尾の改行文字をトリミングしないために起こります。

irb(main):001:0> File.read("wordslist.txt") 
=> "hello\nbye\n" 
irb(main):002:0> File.readlines("wordslist.txt") 
=> ["hello\n", "bye\n"] 
irb(main):003:0> gets 
bye 
=> "bye\n" 

あなたの辞書には "さようなら\ n" は含まれており、 "BYKの\ n" を入力すると、3試合、 "B"、 "Y"、および "\ nは" 実際にあります。あなたが "by \ n"と入力した場合、改行文字は一致しません。改行文字は、入力文字列の長さが同じである場合にのみ一致し、返される値は期待していたよりも1倍多くなります。

これを修正するには、文字を比較する前に末尾の空白を削除するには、両方の文字列の.chompを呼び出すことができます。

word = File.readlines("wordslist.txt").sample.chomp; 
guess = gets.chomp 
same = guess.each_char.zip(word.each_char).select{ |g,w| g == w }.size 

ヒント:あなたは.count代わりの.select.sizeを使用することができます。

same = guess.each_char.zip(word.each_char).count{ |g,w| g == w } 
+0

素晴らしい、ありがとう。 – Anthemius

0
def number_same_position(guess, word) 
    (0..word.size-1).count { |i| guess[i] == word[i] } 
end 

number_same_position("boat", "board") #=> 3 
number_same_position("bait", "board") #=> 1 
number_same_position("sulk", "board") #=> 0 
number_same_position("boater", "board") #=> 3 
number_same_position("", "board")  #=> 0 

3つのドット((0...word.size))しかし、私は常に2つのドットを使用します。 i >= string.sizeの場合はstring[i] #=> nilを呼び出してください。