我有一个包含功率范围颜色列表rangers = ["red", "blue", "yellow", "pink", "black"]
我想验证给定的参数是否与功率范围颜色匹配,但问题是参数可能有不同的情况(大写,小写,混合)。
示例:
def validate_rangers(color)
rangers = ["red", "blue", "yellow", "pink", "black"]
rangers.grep(color).any?
end
validates_rangers("red") #=> true
但
validates_rangers("Red") #=> false. Needs to be true.
如何使用不区分大小写的grep?
答案 0 :(得分:5)
您可以使用不敏感标记:
rangers.grep(/#{color}/i).any?
由于该标志使正则表达式不敏感,它将匹配red
<强> Working demo 强>
def validate_rangers(color)
rangers = ["red", "blue", "yellow", "pink", "black"]
rangers.grep(/#{color}/i).any?
end
答案 1 :(得分:4)
解决此问题的更惯用的Ruby方式如下:
# Define a constant that defines the colors once and once only.
RANGERS = ["red", "blue", "yellow", "pink", "black"]
def validates_rangers(color)
# Check against an arbitrary object that may or may not be a string,
# and downcase it to match better.
RANGERS.include?(color.to_s.downcase)
end
如果您经常这样做,可能需要使用Set
来优化效果:
RANGERS = Set.new(["red", "blue", "yellow", "pink", "black"])
这不需要任何代码更改,但查找速度要快得多。
如果您打算使用正则表达式:
# Construct a case-insensitive regular expression that anchors to the
# beginning and end of the string \A...\z
RANGERS = Regexp.new(
'\A(?:%s)\z' % Regexp.union("red", "blue", "yellow", "pink", "black"),
Regexp::IGNORECASE
)
def validates_rangers(color)
# Double negation returns true/false instead of MatchData
!!RANGERS.match(color.to_s.downcase)
end
validates_rangers("Red")
# => true
validates_rangers("dred")
# => false
答案 2 :(得分:3)
您可以在参数
中使用downcasedef validate_rangers(color)
rangers = ["red", "blue", "yellow", "pink", "black"]
rangers.include?(color.downcase)
end
答案 3 :(得分:0)
Array.grep使用===进行比较。要实际使用正则表达式作为比较,您可以将数组更改为正则表达式而不是字符串:
rangers = [/red/, /blue/, /yellow/, /pink/, /black/]
然后在你的比较中,使用正则表达式匹配(=〜)而不是====:
rangers.map{|ranger| ranger =~ color }.any?
要进行不区分大小写的比较,可以将i添加到正则表达式值的末尾。总之,它看起来像这样:
def validate_rangers(color)
rangers = [/red/i, /blue/i, /yellow/i, /pink/i, /black/i]
rangers.map{|ranger| ranger =~ color }.any?
end
答案 4 :(得分:0)
这里不需要正则表达式:
def validate_rangers(color)
rangers = %w|red blue yellow pink black|
rangers.any? &color.downcase.method(:==)
end