【问题标题】:How to check for Hash value in an array?如何检查数组中的哈希值?
【发布时间】:2016-10-10 18:16:10
【问题描述】:

这是我的设置

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 语句将始终为真)?

【问题讨论】:

    标签: arrays ruby key-value hashset


    【解决方案1】:

    在您的代码中,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
    

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

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

    【讨论】:

    • 然后它将哈希集推送到 teamList 数组,该数组为 if 语句提供了一些可比较的内容,即使这样它也返回 true;这就是我的问题所在
    • @EXC3ll3NTrhyTHM 我已经编辑了我的答案,因为我不知道你的数据集我必须创建问题对象
    • 最好用.detect来实现has_assignee?
    • @SergioTulentsev 感谢您指出.detect 看看 Enumerable 类,.any? 也可以使用,实际上它更适合,因为它返回一个布尔值
    • 或者 .detect 可能不会在块返回 true 时立即返回
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 2019-03-05
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    相关资源
    最近更新 更多