2013-02-09 109 views
1

我試着寫一個應用程序,從單詞列表中移除的話:檢查數組包含字符串,不區分大小寫

puts "Words:" 
text = gets.chomp 
puts "Words to remove:" 
remove = gets.chomp 
words = text.split(" ") 
removes = remove.split(" ") 
words.each do |x| 
    if removes.include.upcase? x.upcase 
     print "REMOVED " 
    else 
     print x, " " 
    end 
end 

我怎麼會做出這種區分大小寫? 我試過把.upcase放在那裏,但沒有運氣。

+0

在哪裏?目前尚不清楚你嘗試過什麼。 if語句中的 – 2013-02-09 22:48:46

+0

。 編輯OP – krtek 2013-02-09 22:51:40

+0

你不需要每個元素的情況? – 2013-02-09 22:54:06

回答

3
words.each do |x| 
    if removes.select{|i| i.downcase == x.downcase} != [] 
     print "REMOVED " 
    else 
     print x, " " 
    end 
end 

array#select將來自陣列如果塊產生true選擇的任何元件。因此,如果select不選擇任何元素並返回一個空數組,它不在數組中。


編輯

您還可以使用if removes.index{|i| i.downcase==x.downcase}。它的性能比select更好,因爲它不創建臨時數組,並在每次找到第一個匹配時返回。

2
puts "Words:" 
text = gets.chomp 
puts "Words to remove:" 
remove = gets.chomp 
words = text.split(" ") 
removes = remove.upcase.split(" ") 

words.each do |x| 
    if removes.include? x.upcase 
    print "REMOVED " 
    else 
    print x, " " 
    end 
end 
+0

不是我所期望的,但它的工作原理。 (我優先保留刪除原來的外殼)。 – krtek 2013-02-09 22:58:18

+1

然後保持它正常的情況下,而是使用:'removes.any? {| r | r.upcase == x.upcase}' – 2013-02-09 23:05:43

相關問題