[英]Remove element from array unless has a certain value in Rails
我有一個“名稱”數組,並且僅當該名稱是該數組中的唯一名稱時,我才想顯示當前用戶的名稱。 如果數組中還有其他名稱,則我不想顯示當前用戶的名稱。
當前,我正在列出名稱並排除當前用戶的名稱,但是如果它是數組中的唯一名稱,則不想排除當前用戶的名稱。 我希望我能解釋清楚。
我的代碼現在:
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
這應該工作:
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
我將第一行移到Conversation#users
方法中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.