1

I am trying to compare two arrays and display different results if there are matching values or not.

@codes.each do |code|
  accessible_codes = code.roles.pluck(:role_id)
  current_users_roles = current_user.roles.pluck(:role_id)

  (accessible_codes & current_users_roles).each {|i|
    if i
      puts "accessible"
    else
      puts "not accessible"
    end
  }
end

Currently I only get the "accessible" output. How do I compare each and get both true and false cases?

1 Answer 1

2

You are iterating over the intersection of those two arrays. It sounds like you want to check whether or not there are any elements in that intersection. You'd want something like this:

current_users_roles = current_user.roles.pluck(:role_id)
@codes.each do |code|
  accessible_codes = code.roles.pluck(:role_id)
  if (accessible_codes & current_users_roles).empty?
    puts "not accessible"
  else
    puts "accessible"
  end
end
Sign up to request clarification or add additional context in comments.

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.