use*_*384 0 ruby arrays ruby-on-rails ruby-on-rails-4
我有一个"名称"数组,我想显示当前用户的名称,只要它是数组中唯一的名称.如果数组中还有其他名称,我不想显示当前用户的名称.
目前,我列出了名称并排除了当前用户的名称,但如果它是数组中唯一的名称,则不希望排除当前用户的名称.我希望我解释说没关系.
我的代码现在:
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
Run Code Online (Sandbox Code Playgroud)
这应该工作:
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
Run Code Online (Sandbox Code Playgroud)
我会把第一行移到一个Conversation#users方法中.
| 归档时间: |
|
| 查看次数: |
366 次 |
| 最近记录: |