查找字符串中出现最多的字符/字母

时间:2015-05-31 05:09:56

标签: ruby string

尝试在字符串中获取最常出现的字母。

到目前为止:

puts "give me a string"
words = gets.chomp.split
counts = Hash.new(0)
words.each do |word|
  counts[word] += 1
end

比请求字符串更进一步。我做错了什么?

4 个答案:

答案 0 :(得分:1)

如果你在irb中运行它,那么计算机可能会认为您输入的ruby代码是要分析的文本:

irb(main):001:0> puts "give me a string"
give me a string
=> nil
irb(main):002:0> words = gets.chomp.split
counts = Hash.new(0)
words.each do |word|
counts[word] += 1
end=> ["counts", "=", "Hash.new(0)"]
irb(main):003:0> words.each do |word|
irb(main):004:1* counts[word] += 1
irb(main):005:1> end
NameError: undefined local variable or method `counts' for main:Object
    from (irb):4:in `block in irb_binding'
    from (irb):3:in `each'
    from (irb):3
    from /Users/agrimm/.rbenv/versions/2.2.1/bin/irb:11:in `<main>'
irb(main):006:0> 

如果你将它包裹在某种块中,你就不会感到困惑:

begin
  puts "give me a string"
  words = gets.chomp.split
  counts = Hash.new(0)
  words.each do |word|
    counts[word] += 1
  end
  counts
end

给出

irb(main):001:0> begin
irb(main):002:1*   puts "give me a string"
irb(main):003:1>   words = gets.chomp.split
irb(main):004:1>   counts = Hash.new(0)
irb(main):005:1>   words.each do |word|
irb(main):006:2*     counts[word] += 1
irb(main):007:2>   end
irb(main):008:1>   counts
irb(main):009:1> end
give me a string
foo bar
=> {"foo"=>1, "bar"=>1}

然后你可以研究split本身并不是你想要的事实。 :)

答案 1 :(得分:0)

这应该有效:

puts "give me a string"
result = gets.chomp.split(//).reduce(Hash.new(0)) { |h, v| h.store(v, h[v] + 1); h }.max_by{|k,v| v}
puts result.to_s

输出:

@Alan ➜  test rvm:(ruby-2.2@europa)  ruby test.rb
give me a string
aa bbb cccc ddddd
["d", 5]

或者在irb:

:008 > 'This is some random string'.split(//).reduce(Hash.new(0)) { |h, v| h.store(v, h[v] + 1); h }.max_by{|k,v| v}
 => ["s", 4]

答案 2 :(得分:-1)

不是逐字逐句地计算,而是可以立即处理整个字符串。

  str = gets.chomp
  hash = Hash.new(0)
  str.each_char do |c|
    hash[c] += 1 unless c == " " #used to filter the space
  end

获得字母数后,您可以使用

找到计数最高的字母
max = hash.values.max

然后将其与哈希中的密钥匹配,您就完成了:)

puts hash.select{ |key| hash[key] == max }

或者简化上述方法

hash.max_by{ |key,value| value }

这种紧凑形式是:

  hash = Hash.new(0)
  gets.chomp.each_char { |c| hash[c] += 1 unless c == " " }
  puts hash.max_by{ |key,value| value }

答案 3 :(得分:-1)

返回给定字符串中出现最高的字符:

puts "give me a string"

characters = gets.chomp.split("").reject { |c| c == " " }
counts = Hash.new(0)

characters.each { |character| counts[character] += 1 }

print counts.max_by { |k, v| v }