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

标签 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 放在那里但没有成功。

最佳答案

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.dow​​ncase==x.downcase}.它比 select 执行得更好,因为它不会创建临时数组并在找到第一个匹配项时返回。

关于ruby - 检查数组是否包含字符串,不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14792448/

相关文章:

sql - 优化查询,使 Order by random 运行得更快

ios - 葫芦 iOS : how to get value using query command

ruby - 在 Linux 下的 Ruby 中以不区分大小写的方式打开文件

ruby-on-rails - 如果运行多个池,延迟作业会初始化多少个 Rails 实例

c - 在 Intel X_86 和 ARM 架构上转储两个相邻的 C 数组时出现奇怪的不同结果

c - 初始化一个二维字符串数组并打印

c# - 将 XML 读入数组,不断出现错误

c# - C# 中的静态常量

javascript - 当字符串可能为空时确定 Node JS 中的字符串长度

字符串或字符串常量