以下是我的代码。如何简化此代码?
我只是想避免太多&&
条件。
假设我有两个网址:
ipt_string = www.abc.com/catogories/profile/heels/
ipt_string = www.abc.com/me/payment/auth/
def to_uri(ipt_string)
point = ipt_string.gsub('{', '#{')
if @profile &&
!point.include?('/catogories/') &&
!point.include?('/profile/') &&
!point.include?('/heels/') &&
!point.include?('/me/') &&
!point.include?('/payment/') &&
!point.include?('/auth/')
{ ... }
答案 0 :(得分:5)
第一个选项:
if @profile && (%w(a b c d e) & point.split('')).none?
其他选择是使用正则表达式:
if @profile && !point.match(/[abcde]/)
正如@Stefan在评论中指出的那样,版本有点短:
if @profile && point !~ /[abcde]/
关于检查的OP评论
网址是否包含
'/heels/'
由于它是您正在寻找的特定字符串,我认为检查包含是否会:
if @profile && !point.include?('/heels/')
要在list_of_strings
内检查point
,您可以选择:
if @profile && list_of_strings.none? { |str| point.include?(str) }
答案 1 :(得分:2)
您可以将match
与正则表达式一起使用:
> "a string of text".match(/[abcde]/).nil?
=> false
> "a string of text".match(/[zq]/).nil?
=> true
答案 2 :(得分:0)
if @profile && (/[abcde]/.match(point)).nil?
或
if @profile && (/[abcde]/ =~ point).nil?