下面是我的代码。如何简化这段代码?
我只是想避免太多的 &&
条件。
假设我有两个 url:
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/')
{ ... }
最佳答案
第一个选项:
if @profile && (%w(a b c d e) & point.split('')).none?
其他选择是使用正则表达式:
if @profile && !point.match(/[abcde]/)
正如@Stefan 在评论中指出的,略短的版本:
if @profile && point !~ /[abcde]/
关于OP对检查的评论
whether the url contains
'/heels/'
因为它是您要查找的特定字符串,我认为检查是否包含:
if @profile && !point.include?('/heels/')
编辑
有一个list_of_strings
,你想在一个点
中检查,你可以去:
if @profile && list_of_strings.none? { |str| point.include?(str) }
关于ruby - 如何在 ruby 中简化太多的 AND/OR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39618202/