Ruby返回匹配的字符大小

时间:2017-09-24 03:33:28

标签: ruby string

我正在尝试制作一个游戏,其中涉及它返回您猜测的字符数量,这些字符位于随机生成的单词的正确位置(例如,单词是“board”,然后您输入“boat” “,你得到2/5,你进入”董事会“,你得到5/5)。

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。只是想看看我做错了什么。

2 个答案:

答案 0 :(得分: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"

当你的词典包含“bye \ 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 }

答案 1 :(得分: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

可以改为使用三个点((0...word.size)),但我总是使用两个点。在string[i] #=> nil时召回i >= string.size

相关问题