每次执行时出错(Ruby)
我正在用ruby做一个审核员,这个审核员今天早上开始做得很好(使用单个单词,用户输入的内容可以省略),但是现在我已经尝试实现一个单词列表,它每次执行时出错(Ruby),ruby,Ruby,我正在用ruby做一个审核员,这个审核员今天早上开始做得很好(使用单个单词,用户输入的内容可以省略),但是现在我已经尝试实现一个单词列表,它将字符串搜索的次数与单词列表中的单词搜索的次数一样多,只对它进行一到两次审查。我的代码如下 #by Nightc||ed, ©2015 puts "Enter string: " text = gets.chomp redact = File.read("wordlist.txt").split(" ") words = text.split(" ") re
将字符串搜索的次数与单词列表中的单词搜索的次数一样多,只对它进行一到两次审查。我的代码如下
#by Nightc||ed, ©2015
puts "Enter string: "
text = gets.chomp
redact = File.read("wordlist.txt").split(" ")
words = text.split(" ")
redact.each do |beep|
words.each do |word|
if word != beep
print word + " "
else
print "[snip] "
end
end
end
sleep
我有点理解它为什么不工作,但我不知道如何修复它
任何帮助都将不胜感激。有一种比遍历每个数组更简单的方法。Array#include
方法可以很容易地用来查看单词是否包含在您的编辑列表中
下面是一些代码,它们应该按照您希望原始代码的方式运行:
puts "Enter string: "
text = gets.chomp
redact = File.read("wordlist.txt").split(" ")
words = text.split(" ")
words.each do |word|
if redact.include? word
print "[snip] "
else
print word + " "
end
end
清除文本变得非常棘手。你要注意的一件事是单词边界。由于puctuation,在空格上拆分会让很多beep单词通过。比较下面示例代码的前两个结果
接下来,使用点字、空格等将拆分的文本重新组合成预期的形式将是一项相当具有挑战性的工作。您可能想考虑使用ReGEX作为用户评论的小前提。见第三个结果
如果您将此作为一个学习练习,这很好,但是如果应用程序很敏感,您可能会对错误进行热处理以发出单词,那么您可能需要寻找一个现有的经过良好测试的库
#!/usr/bin/env ruby
# Bleeper
scifi_curses = ['friggin', 'gorram', 'fracking', 'dork']
text = "Why splitting spaces won't catch all the friggin bleeps ya gorram, fracking dork."
words = text.split(" ")
words.each do |this_word|
puts "bleep #{this_word}" if scifi_curses.include?(this_word)
end
puts
better_words = text.split(/\b/)
better_words.each do |this_word|
puts "bleep #{this_word}" if scifi_curses.include?(this_word)
end
puts
bleeped_text = text # keep copy of original if needed
scifi_curses.each do |this_curse|
bleeped_text.gsub!(this_curse, '[bleep]')
end
puts bleeped_text
您应该得到以下结果:
bleep friggin
bleep fracking
bleep friggin
bleep gorram
bleep fracking
bleep dork
Why splitting spaces won't catch all the [bleep] bleeps ya [bleep], [bleep] [bleep].