如何检查数组中的哈希值?

How to check for Hash value in an array?

这是我的设置

project_JSON = JSON.parse

teamList = Array.new

project = Hash.new()
project["Assignee Name"] = issue["fields"]["assignee"]["displayName"]
project["Amount of Issues"] = 0

if !teamList.include?(issue["fields"]["assignee"]["displayName"])
    project_JSON.each do |x|
        project["Amount of Issues"] += 1
        teamList.push(project)
end

我在使用这条线时遇到了问题。

if !teamList.include?(issue["fields"]["assignee"]["displayName"])

它始终 returns 正确,即使在 .push 之后也是如此。我想制作一个团队成员数组,并列出他们的名字在我的 JSON 中出现的次数。我做错了什么以及我如何在 if 语句中动态引用哈希值(那是我认为它错误的地方,因为如果我说 .include?(issue["fields"]["assignee"]["displayName"]) 错误,那么它的 nil 和 if 语句将永远为真)?

在你的代码中 teamList 是一个空数组,所以它不会 include? 任何东西,它总是 return false。现在,因为您正在使用 ! 运算符,所以它总是 return 为真。

编辑

如果理解正确,您必须遍历数组检查每个元素的指定值。

下面是一种方法,请注意,我将键替换为符号,因为这是 Ruby 中的一个好习惯:

issue = {
    :fields => {
        :assignee => {
            :displayName => 'tiago'
        }
    }
}

teamList = Array.new

def teamList.has_assignee?(assignee)
    self.each do |e|
        return e[:assignee] == assignee
    end
    false
end


project = Hash.new
project[:assigneeName] = issue[:fields][:assignee][:displayName]
project[:amountOfIssues] = 0 

teamList.push(project) unless teamList.has_assignee? issue[:fields][:assignee][:dsiplayName] 
teamList.push(project) unless teamList.has_assignee? issue[:fields][:assignee][:dsiplayName] 


puts teamList.inspect # only one object here

正如 Sergio 指出的那样,您可以使用 .detect

def teamList.has_assignee?(assignee)
        self.detect { |e| e[:assigneeName] == assignee }
end