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

时间:2016-10-10 18:16:10

标签: arrays ruby key-value hashset

继承我的设置

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"])

即使在.push之后它也总是返回true。我想创建一个我的团队成员阵列,并列出他们的名字出现在我的JSON中的次数。我做错了什么以及如何在if语句中动态引用哈希值(这就是我认为错误的地方,因为如果我说.include?(issue["fields"]["assignee"]["displayName"])错了那么它的nil和if语句总是为真)?

1 个答案:

答案 0 :(得分:0)

在您的代码中teamList是一个空数组,因此它不会include?任何内容,它将始终返回false。现在因为您使用!运算符,它总是返回true。

修改

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

下面是一种方法,请注意,我替换了符号键,因为它是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

正如塞尔吉奥指出你可以使用.detect

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