我正在尝试编写一个从单词列表中删除单词的应用程序:
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
放在那里但没有成功。
最佳答案
words.each do |x|
if removes.select{|i| i.downcase == x.downcase} != []
print "REMOVED "
else
print x, " "
end
end
array#select
将在 block 产生 true 时从数组中选择任何元素。所以如果 select
没有选择任何元素并返回一个空数组,则它不在数组中。
编辑
你也可以使用 if removes.index{|i| i.downcase==x.downcase}
.它比 select
执行得更好,因为它不会创建临时数组并在找到第一个匹配项时返回。
关于ruby - 检查数组是否包含字符串,不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14792448/