2015-06-06 42 views
-2
puts "Please Enter a text string: " 
user_input = gets.chomp 
puts "What word(s) would you like to redact?" 
user_redacted = gets.chomp 

user_input_words = user_input.split(" ") 
user_redacted_words = user_redacted.split(" ") 

user_input_words.each do |user_input_word| 
    if user_input_word == user_redacted_words 
     print "REDACTED " 
    else 
     print user_input_word + " " 
    end 
end 

代碼將不會在用戶選擇編輯的單詞上打印編輯。但它會以純文本格式打印出user_input_words,而不是[「an」「array」]格式。 user_input_word陣列不會匹配user_redacted_words陣列,找到應該被刪除的單詞嗎?無法弄清楚爲什麼Ruby不合作

預先感謝您!

+1

'user_input_word'在block是一個String,而user_redacted_words是一個Array,它們永遠不會相等。你想達到什麼目的? –

+0

啊,所以我試圖將一個字符串與一個數組進行比較。而不是一個字來編輯,我試圖讓多個單詞來編輯。我認爲我的'user_redacted_words = user_redacted.split(「」)'會將編輯的字符串更改爲數組? – aphrodeeziac

+0

你的問題是什麼? – sawa

回答

3

您想要檢查當前單詞是否包含在編輯單詞列表中。因此,而不是檢查,如果一個字等於單詞的數組:

if user_input_word == user_redacted_words 

你想,而不是檢查,如果這個詞包含的刪節字陣列中:

if user_redacted_words.include? user_input_word 
+0

哦,我的天哪,工作!我沒有練過「.include?」很多東西。還在學習Ruby。你能告訴我爲什麼我的==沒有/不會工作嗎? (只是爲了理解。) – aphrodeeziac

+1

當然!因此'user_input_word'將是他們在第一個輸入中鍵入的一個單詞,比如'toast'。 'user_redacted_words'將會是從他們在第二個輸入處輸入的內容(可能是'['bananas','toast','pineapples']')創建的一組單詞(單詞列表)。現在很清楚,「吐司」不等於'['bananas','toast','pineapples']',所以當你使用'=='比較它們時,它永遠不會是真的。然而'''香蕉','toast','pineapples']中包含''toast'',所以當你使用'include?'方法時,如果這個單詞位於redacted數組中,它將返回true話。 – JKillian

+0

您可以閱讀文檔中的['include?'方法](http://ruby-doc.org/core-2.2.0/Array.html#method-i-include-3F)。它接受一個參數,如果參數在數組中,則返回true;如果參數不在數組中,則返回false。 – JKillian

相關問題