相关疑难解决方法(0)

如何找到最大值哈希的密钥?

我有以下哈希 {"CA"=>2, "MI"=>1, "NY"=>1}

如何使用ruby返回最大键值对?我希望它返回"CA"

ruby hash

103
推荐指数
5
解决办法
6万
查看次数

字符串中最常见的单词

我是Ruby的新手,并尝试编写一个方法,该方法将返回字符串中最常见的单词数组.如果有一个具有高计数的单词,则应返回该单词.如果高计数绑定了两个单词,则两者都应以数组形式返回.

问题是,当我通过第二个字符串时,代码只计算"单词"两次而不是三次.当第三个字符串通过时,它返回"it",计数为2,这没有任何意义,因为"它"的计数应为1.

def most_common(string)
  counts = {}
  words = string.downcase.tr(",.?!",'').split(' ')

  words.uniq.each do |word|
    counts[word] = 0
  end

  words.each do |word|
    counts[word] = string.scan(word).count
  end

  max_quantity = counts.values.max
  max_words = counts.select { |k, v| v == max_quantity }.keys
  puts max_words
end

most_common('a short list of words with some words') #['words']
most_common('Words in a short, short words, lists of words!') #['words']
most_common('a short list of words with some short words in it') #['words', 'short']
Run Code Online (Sandbox Code Playgroud)

ruby arrays string hash

4
推荐指数
1
解决办法
2418
查看次数

Ruby:如何在哈希中找到最大值的键?

您好我正在尝试找到哈希值中的最大值.我在谷歌搜索,我发现这个代码:

def largest_hash_key(hash)
  key = hash.sort{|a,b| a[1] <=> b[1]}.last
  puts key
end

hash = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
largest_hash_key(hash)
Run Code Online (Sandbox Code Playgroud)

在此代码中,"puts"打印出最大的键和值ex y300.那么,我如何修改代码以找到最大值并将其键入to_s变量?

ruby hash max

3
推荐指数
1
解决办法
5719
查看次数

标签 统计

hash ×3

ruby ×3

arrays ×1

max ×1

string ×1