-2

这是我的代码:

class String
  def frequency
    chars.each_with_object(Hash.new(0)) do |char, h|
      h["#{char.upcase}:"] += 1 if char[/[[:alpha:]]/]
    end
  end
end

我试过用更小的代码分解它,比如使用 .times do 循环,但我想不通

例如:

str = "\*"
h["A:"] = count('a').times do
str
end
4

1 回答 1

1

您是否尝试执行以下操作:

counts = 'aassssvvvvv'.frequency
counts.each{|key,count| puts key + '*'*count}

# A:**
# S:****
# V:*****

Or if you want to change the key you can do:

counts.each{|key,amount| counts[key] = '*'*amount}
于 2013-11-14T18:26:54.987 回答