brad
brad

Reputation: 1695

If object is contained in an array logic - Ruby

Conceptually I am trying to display a list of users in a search result list and have it say 'add as friend' if the user is not a friend and 'unfriend' if they are a friend.

The basic question I need answered to do this is how to say if an user ID exists in an array. I created a friends array which contains all the id numbers of my friends and need to essentially write;

if user_in_search_results_id = id in the array, unfriend, otherwise add as friend.

the 'if user_in_search_results_id = id anywhere in the array' is where i am stuck.

I have tried .where(user_in_search_results_id == @friends) and that did not work. @friends is friend array. I have also tried the .select method without luck.

Thanks

Upvotes: 0

Views: 82

Answers (3)

tigeravatar
tigeravatar

Reputation: 26640

I think you're looking for the include? method

user_in_search_results_id.each {|id| @friends.include?(id) ? unfriend(id) : add_as_friend(id)}

Upvotes: 2

squiguy
squiguy

Reputation: 33370

I would use Enumerable#detect.

@friends.detect { |id| user_in_search_results_id == id } 

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118271

The basic question I need answered to do this is how to say if an user ID exists in an array.

You can do

friends_array.member?(user_id) ? "unfriend" : "add friend"

Upvotes: 0

Related Questions