以下是我的代码.如何简化此代码?
我只是想避免太多的&&条件.
假设我有两个网址:
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/')
{ ... }
Run Code Online (Sandbox Code Playgroud)
第一种选择:
if @profile && (%w(a b c d e) & point.split('')).none?
Run Code Online (Sandbox Code Playgroud)
其他选择是使用正则表达式:
if @profile && !point.match(/[abcde]/)
Run Code Online (Sandbox Code Playgroud)
正如@Stefan在评论中指出的那样,版本有点短:
if @profile && point !~ /[abcde]/
Run Code Online (Sandbox Code Playgroud)
至于OP对评论的评论
网址是否包含
'/heels/'
由于它是您正在寻找的特定字符串,我认为检查包含将会:
if @profile && !point.include?('/heels/')
Run Code Online (Sandbox Code Playgroud)
有一个list_of_strings你想要检查的point,你可以去:
if @profile && list_of_strings.none? { |str| point.include?(str) }
Run Code Online (Sandbox Code Playgroud)