Ruby 谁能给我一些建议,如何用星号代替字母的数目?

Ruby 谁能给我一些建议,如何用星号代替字母的数目?,ruby,Ruby,下面是我的代码和输出,我想让它,而不是说发生了多少次,它将输出字母以星号形式出现的次数 对于exmaple,如果“a”在一句话中出现四次,则输出将产生: “a”:**** the_file='C:\Users\Jack\Documents\Ruby\Lab1\lyric.txt' h = Hash.new f = File.open(the_file, "r") f.each_line { |line| words = line.split(//) words.each { |w|

下面是我的代码和输出,我想让它,而不是说发生了多少次,它将输出字母以星号形式出现的次数

对于exmaple,如果“a”在一句话中出现四次,则输出将产生:
“a”:****

the_file='C:\Users\Jack\Documents\Ruby\Lab1\lyric.txt'
h = Hash.new
f = File.open(the_file, "r")
f.each_line { |line|
  words = line.split(//)
  words.each { |w|
    if h.has_key?(w)
      h[w] = h[w] + 1
    else
      h[w] = 1
    end
  }
}

# sort the hash by value, and then print it in this sorted order

h.sort{|a,b| a[1]<=>b[1]}.each { |elem|
  puts "\"#{elem[0]}\" : #{elem[1]} occurrences"
}
文件='C:\Users\Jack\Documents\Ruby\Lab1\lyric.txt'
h=散列。新
f=文件。打开(文件“r”)
f、 每条{线|
字=行。拆分(//)
单词.each{| w|
如果h.有_键?(w)
h[w]=h[w]+1
其他的
h[w]=1
终止
}
}
#按值对哈希进行排序,然后按此排序顺序打印
h、 排序{a,b{a[1]b[1]}。每个{元素|
放置“\”{elem[0]}\”:{elem[1]}个事件”
}
我当前程序和输出的屏幕截图

+
对于串联,
字符串
*
数字
是将某些字符串数字重复几次。

而不是
{elem[1]}发生次数
你只需要写
{'*'*elem[1]}


有关更多详细信息,请参阅。

对于Ruby中的字符串,可以对其使用数学运算符。因此,您知道字母出现了多少次(在
elem[1]
中)。在这种情况下,您可以将星号符号乘以该值:


“\”{elem[0]}:{'*'*elem[1]}\”

我想展示另一种实现字数计算的可能替代方法。 让文件读取分开,让我们考虑下面的字符串:

line = 'Here is my code and output below, i would like to have it so that instead of saying how many occurrences, it would output the number of times the letter appears in asterisk form.'

h = Hash.new(0)
line.downcase.each_char{ |ch| h[ch] += 1 if ('a'..'z').include? ch }
h.to_a.sort_by(&:last).reverse.each { |ch, count| puts "#{ch}: " + "*" * count}
  • 使用
    default=0初始化哈希,允许您在不检查键是否存在的情况下开始计数:
  • 通过循环遍历该行
  • 我只计算不区分大小写的字母,由你决定
  • 对于排序,请将散列更改为具有
  • 用于打印直方图,如其他帖子所示

您能否在问题中提供一个最简单的代码工作示例,这样我们就不必键入代码就可以进行调试?很抱歉,我现在就这样做
单词
不是单词。标准的Ruby样式是在块在多行上表示时使用。因此,与其用括号括起来,不如说在最后一点结束?我已尝试替换文件,所以它将有输入,而不是像下面,对不起,我很新的这个
print“请输入任意长度的文本:
user\u input=String(gets.chomp)
h=Hash.new
f=user\u input
f.each\u line{code>
line = 'Here is my code and output below, i would like to have it so that instead of saying how many occurrences, it would output the number of times the letter appears in asterisk form.'

h = Hash.new(0)
line.downcase.each_char{ |ch| h[ch] += 1 if ('a'..'z').include? ch }
h.to_a.sort_by(&:last).reverse.each { |ch, count| puts "#{ch}: " + "*" * count}