This seems like a foolishly simple problem. I’m searching through a list of users, using a bitwise operator to determine whether first and last names match the provided term (I didn’t write this code, it’s legacy).
Now I need to add in a third condition – that their state is not ‘disabled.’ Without this third condition, the search works as expected. However, when I add the other and statement, it breaks.
@users = User.reject{|user| user.first_name !~ /^#{term}/i && user.last_name !~ /^#{term}/i } #Works as expected - returns users matching 'term'
@users = User.reject{|user| user.first_name !~ /^#{term}/i && user.last_name !~ /^#{term}/i && user.suspended? } # Does not work - returns a full list of active users, as well as any suspended users that match.
@users = User.reject{|user| user.first_name !~ /^#{term}/i && user.last_name !~ /^#{term}/i }
@users.reject!{|user| user.suspended?} # This combination works, but I feel like there should be a way to condense it into a single line
I’ve also tried adding some parentheses around the first two conditions, but that doesn’t help either.
Any help is appreciated
There’s not bitwise operation here,
!~is a negated regex match (think “doesn’t match”).For your actual question:
Basically this says: ‘reject the user if this first_name and last_name don’t match the provided regular expression or if the user is suspended’. Your version only worked for users with invalid names who ALSO where suspended (because of the
&&).