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

4

2 回答 2

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

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


编辑

您也可以使用if removes.index{|i| i.downcase==x.downcase}. 它比它执行得更好,select因为它不创建临时数组并在找到第一个匹配项时返回。

于 2013-02-09T23:03:59.367 回答
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
于 2013-02-09T22:56:20.787 回答