2013-02-09 110 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

相关问题