bonum_cete
bonum_cete

Reputation: 4962

Comparing two arrays for the same values and non-matching values

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?

Upvotes: 1

Views: 310

Answers (1)

Paul Hoffer
Paul Hoffer

Reputation: 12906

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

Upvotes: 2

Related Questions