检查数组是否包含字符串,不区分大小写

时间:2013-02-09 22:41:34

标签: ruby arrays string

我正在尝试编写一个从单词列表中删除单词的应用程序:

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放在那里,但没有运气。

2 个答案:

答案 0 :(得分:3)

words.each do |x| 
    if removes.select{|i| i.downcase == x.downcase} != []
        print "REMOVED "
    else
        print x, " "
    end
end
如果块产生true,

array#select将从数组中选择任何元素。因此,如果select没有选择任何元素并返回一个空数组,则它不在数组中。


修改

您也可以使用if removes.index{|i| i.downcase==x.downcase}。它的性能优于select,因为它不会创建临时数组,只要找到第一个匹配就会返回。

答案 1 :(得分: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