2015-03-24 59 views
0

我正在做一个红宝石审计,今天早上开始罚款(使用单个字,用户输入的内容省略),但现在我试图实现一个单词表,它puts要搜索的字符串的次数与单词表中的单词相同,只能审查一次或两次。我的代码如下。每个执行错误(红宝石)

#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 

我有点理解它为什么不起作用,但我不知道如何解决它。

任何帮助,将不胜感激。

回答

0

有一个比遍历每个数组更简单的方法。可以很容易地使用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 
0

擦洗文本变得非常棘手。你要注意的一件事是字界。因空间分割会让许多嘟嘟的单词由于念头而得以通过。比较下面示例代码的前两个结果。

接下来,将分割文本重新组装到预期形式中,使用punction,spacing等等,将变得非常具有挑战性。您可能要考虑使用正则表达式来预先设定与用户注释一样小的内容。看到第三个结果。

如果你将此作为一种学习练习,那很好,但如果应用程序对敏感的地方很容易受到失败煽风点火的困扰,那么你可能需要寻找一个经过良好测试的库。

#!/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].