繁体   English   中英

从数组中删除元素,除非在Rails中具有特定值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM