2

Currently I have this code:

if !(allowed_params & password_protected_params).empty?

Which means "if anything in allowed_params is also in password_protected_params". This code works, but I find it a bit obfuscated and not friendly to the next developer that looks at this code.

Is there another, more readable way to check if anything in one array exists within another array?

EDIT

The block in question is this:

if !(allowed_params & password_protected_params).empty?
  result = @user.update_with_password(allowed_params)
else
  #only update trivial attributes
  result = @user.update_without_password(allowed_params)
end

In the end I just added a variable to make it more readable (but still open to better suggestions):

needs_password = !(allowed_params & password_protected_params).empty?
if needs_password
  result = @user.update_with_password(allowed_params)
else
  #only update trivial attributes
  result = @user.update_without_password(allowed_params)
end
3
  • Yes: if (allowed_params & password_protected_params).any? Commented Jun 27, 2016 at 0:20
  • I don't mean replacing empty?, I'm mainly wondering if there's a more human (read: non-expert in Ruby) readable way to show "yes, one of the password protected params is in allowed_params". In particular, the [] & [] operator drew blanks from fellow JS devs, and a couple of Ruby devs too. Commented Jun 27, 2016 at 3:46
  • All I was suggesting is that Ruby often allows you to avoid negation (!) by substituting a complementary method, here any? rather than empty?. Your use of & seems perfectly clear. Sadly, your code being obscure is not the only possible explanation for some Ruby developers being unable to comprehend it. Commented Jun 27, 2016 at 7:16

2 Answers 2

2

One ruby way could be

foo = [1, 2]
=> [1, 2]
bar = [1, 3]
=> [1, 3]
baz = [5, 3]
=> [5, 3]

bar.any?{|element| foo.include?(element)}
=> true
baz.any?{|element| foo.include?(element)}
=> false
Sign up to request clarification or add additional context in comments.

Comments

2

There is not official synonym for Array#&. You can refactor your code into another method, and add a comment:

def intersects?(a, b)
 !(a & b).empty?
end

# ...
if intersects? allowed_params, password_protected_params
# ...

Otherwise, you may want to extend the Array class, and define a method or add an alias_method to it:

class Array
  alias_method :intersection, :&    

  def intersects?(array)
    !(self.intersection(array)).empty?
  end
end

[1, 2, 3].intersects? [3, 4, 5] # true

Bear in mind that changing core-classes is not a good-practice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.