Ruby - 迭代嵌套哈希并计算值

发布于 2024-12-10 02:30:57 字数 713 浏览 0 评论 0原文

尽管关于嵌套哈希有很多问题,但我还没有找到任何解决方案来解决我的问题。

我拉入字符串并将每个字符与散列匹配,如下所示:

numberOfChars = {}
string.each_char do |c|
    RULES.each do |key, value|
        if c === key
            numberOfChars[value] += 1
        end
    end
end

这工作正常,会输出类似“a 出现 3 次”的内容,直到我意识到我的散列需要嵌套,类似于:

RULES = {
    :limb {
        :colour {
            'a' => 'foo',
            'b' => 'bar'
        },         
        'c' => 'baz'
    }
}

那么我该怎么办关于获取“叶子”密钥及其值?

当它迭代哈希时,它还需要计算每个键出现的次数,例如“a”出现的次数是否多于“b”?如果是这样,则添加一个到新的哈希值。但我对它在实践中如何工作感到非常困惑,而不知道它将如何开始迭代嵌套哈希。

在我看来,这样做的方式过于复杂,但如果有人有任何指示,他们将不胜感激!

另外,如果还不是很清楚的话,我是 Ruby 新手,所以我可能犯了一些根本性的错误。

Despite there being many questions on nested hashes I've not found any solutions to my problem.

I'm pulling in strings and matching each character to a hash like so:

numberOfChars = {}
string.each_char do |c|
    RULES.each do |key, value|
        if c === key
            numberOfChars[value] += 1
        end
    end
end

This worked fine and would output something like "a appears 3 times" until I realised that my hash needed to be nested, akin to this:

RULES = {
    :limb {
        :colour {
            'a' => 'foo',
            'b' => 'bar'
        },         
        'c' => 'baz'
    }
}

So how would I go about getting the 'leaf' key and it's value?

While it's iterating over the hash it also needs to count how many times each key appears, e.g. does 'a' appear more than 'b'? If so add a to new hash. But I'm pretty lost as to how that would work in practice without knowing how it'll be iterating over a nested hash to begin with.

It just seems to me an overly convoluted way of doing this but if anyone's got any pointers they'd be hugely appreciated!

Also, if it's not painfully clear already I'm new to Ruby so I'm probably making some fundamental mistakes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

讽刺将军 2024-12-17 02:30:57

您在寻找这样的东西吗?

RULES = {
  :limb => {
    :colour => {
      'a' => 'foo',
      'b' => 'bar'
    },
    'c' => 'baz',
    :color => {
      'b' => 'baz'
    }
  }
}

def count_letters(hash, results = {})
  hash.each do |key, value|
    if value.kind_of?(Hash)
      count_letters(value, results)
    else
      results[key] = (results[key] || 0) + 1
    end
  end
  results
end

p count_letters(RULES)

Are you looking for something like this?

RULES = {
  :limb => {
    :colour => {
      'a' => 'foo',
      'b' => 'bar'
    },
    'c' => 'baz',
    :color => {
      'b' => 'baz'
    }
  }
}

def count_letters(hash, results = {})
  hash.each do |key, value|
    if value.kind_of?(Hash)
      count_letters(value, results)
    else
      results[key] = (results[key] || 0) + 1
    end
  end
  results
end

p count_letters(RULES)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文