user2756384
user2756384

Reputation: 33

Remove element from array unless has a certain value in Rails

I have an array of "names" and I would like to display the current user's name ONLY IF there it is the only name in the array. If there are other names in the array, I don't want to show the current user's name.

Currently, I am listing the names and excluding the current user's name, but don't want to exclude the current user's name if it is the only one in the array. I hope I explained that okay.

My code now:

module ConversationsHelper

def other_user_names(conversation)

    users = []
    conversation.messages.map(&:receipts).each do |receipts|
        users << receipts.select do |receipt|
            receipt.receiver != current_user
        end.map(&:receiver)

    end
    users.flatten.uniq.map(&:name).join ', '

end
end

Upvotes: 0

Views: 461

Answers (1)

Stefan
Stefan

Reputation: 114178

This should work:

def other_user_names(conversation)
  # get all users (no duplicates)
  users = conversation.messages.map(&:receipts).map(&:receiver).uniq

  # remove current user if there are more than 1 users
  users.delete(current_user) if users.many?

  # return names
  users.map(&:name).join(', ')
end

I would move the first line into a Conversation#users method.

Upvotes: 5

Related Questions