Tara
Tara

Reputation: 77

Ruby array - comparison customer_id with an array

I have array of numbers which means governings to acces customer:

Controller :

@user_got_these_governings = current_user.governings.map{ |governing| governing.customer_id}

which_customer_is_selected = params[:user][:customer_id]

i need to compare customer_id with an array of numbers:

customer_id: 1

Governings: [7,9,6,2,3,1]

if Governings match with customer_id = true

if not = false

Upvotes: 0

Views: 60

Answers (3)

Shweta Kumari
Shweta Kumari

Reputation: 11

Another possible way to do it is by using .member? method which tells whether an element is a member of the array or not.

Governings: [7,9,6,2,3,1]
Governings.member? params[:user][:customer_id].to_i
=> true

Upvotes: 1

Marelons
Marelons

Reputation: 160

I think that cleanest way to do it is use in? method.

governings = [7,9,6,2,3,1]
params[:user][:customer_id].to_i.in? governings
=> true

Upvotes: 1

javiyu
javiyu

Reputation: 1474

Something like

which_customer_is_selected = @user_got_these_governings.include?(params[:user][:customer_id].to_i)

to_i because you are probably receiving a string in the parameter and you are comparing it with an array of integers.

Upvotes: 1

Related Questions