J.Adhikari J.Adhikari - 1 year ago 56
Ruby Question

How can I simplify too many AND/OR in ruby

Below is my code. How to simplify this code?

I just want to avoid too many


Suppose I've two 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/') &&
{ ... }

Answer Source

First option:

if @profile && (%w(a b c d e) & point.split('')).none?

Other option would be to use a regex:

if @profile && !point.match(/[abcde]/)

As @Stefan pointed in comments, somewhat shorter version:

if @profile && point !~ /[abcde]/

As to the OP comment on the checking

whether the url contains '/heels/'

Since it is a specific string of characters you're looking for, I think checking for inclusion would do:

if @profile && !point.include?('/heels/')


Having a list_of_strings that you want to check for within a point, you could go with:

if @profile && list_of_strings.none? { |str| point.include?(str) }