如何通过在Ruby中迭代数组来创建直方图

如何通过在Ruby中迭代数组来创建直方图,ruby,arrays,histogram,Ruby,Arrays,Histogram,所以我被告知重写这个问题并概述我的目标。他们让我对数组进行迭代,并“使用.each迭代频率,并将每个单词及其频率打印到控制台…在单词及其频率之间留出一个空格,以便于阅读。” 为什么它不能将字符串转换成整数?我做错了什么?我会按以下方式做: puts "Type something profound please" text = gets.chomp.split 我在这里调用了方法 我调用了下面的方法 现在运行代码: (arup~>Ruby)$ ruby so.rb Type someth

所以我被告知重写这个问题并概述我的目标。他们让我对数组进行迭代,并“使用.each迭代频率,并将每个单词及其频率打印到控制台…在单词及其频率之间留出一个空格,以便于阅读。”

为什么它不能将字符串转换成整数?我做错了什么?

我会按以下方式做:

puts "Type something profound please"
text = gets.chomp.split
我在这里调用了方法

我调用了下面的方法

现在运行代码:

(arup~>Ruby)$ ruby so.rb
Type something profound please
foo bar foo biz bar baz
foo has a freuency count 2
bar has a freuency count 2
biz has a freuency count 1
baz has a freuency count 1
(arup~>Ruby)$ 
请尝试以下代码:

puts "Type something profound please"
words = gets.chomp.split #No need for the test variable

frequencies = Hash.new 0
words.each {|word| frequencies[word] += 1}
words.uniq.each {|word| puts "#{word} #{frequencies[word]}"} 
#Iterate over the words, and print each one with it's frequency.
chunk是一种很好的方法。它返回一个由2个元素数组组成的数组。第一个是块的返回值,第二个是块返回该值的原始元素数组:

words = File.open("/usr/share/dict/words", "r:iso-8859-1").readlines
p words.chunk{|w| w[0].downcase}.map{|c, words| [c, words.size]}
=> [["a", 17096], ["b", 11070], ["c", 19901], ["d", 10896], ["e", 8736], ["f", 6860], ["g", 6861], ["h", 9027], ["i", 8799], ["j", 1642], ["k", 2281], ["l", 6284], ["m", 12616], ["n", 6780], ["o", 7849], ["p", 24461], ["q", 1152], ["r", 9671], ["s", 25162], ["t", 12966], ["u", 16387], ["v", 3440], ["w", 3944], ["x", 385], ["y", 671], ["z", 949]]

为什么
反向
按需求排序?:-)非常感谢Linuxios。这起作用了。我得回去看看我做错了什么。我们还没有了解到.uniq方法,但是看起来这就是造成差异的原因,所以我将查找它,以便我可以在将来自己使用它future@user3324987:当然可以。原始代码中的问题是,您需要在循环中输入put,而不需要所有排序
uniq
非常简单,它只返回数组,没有任何重复项。所以,
[“hi”,“hi”,“the”]
变成了
[“hi”,“the”]
(arup~>Ruby)$ ruby so.rb
Type something profound please
foo bar foo biz bar baz
foo has a freuency count 2
bar has a freuency count 2
biz has a freuency count 1
baz has a freuency count 1
(arup~>Ruby)$ 
puts "Type something profound please"
words = gets.chomp.split #No need for the test variable

frequencies = Hash.new 0
words.each {|word| frequencies[word] += 1}
words.uniq.each {|word| puts "#{word} #{frequencies[word]}"} 
#Iterate over the words, and print each one with it's frequency.
words = File.open("/usr/share/dict/words", "r:iso-8859-1").readlines
p words.chunk{|w| w[0].downcase}.map{|c, words| [c, words.size]}
=> [["a", 17096], ["b", 11070], ["c", 19901], ["d", 10896], ["e", 8736], ["f", 6860], ["g", 6861], ["h", 9027], ["i", 8799], ["j", 1642], ["k", 2281], ["l", 6284], ["m", 12616], ["n", 6780], ["o", 7849], ["p", 24461], ["q", 1152], ["r", 9671], ["s", 25162], ["t", 12966], ["u", 16387], ["v", 3440], ["w", 3944], ["x", 385], ["y", 671], ["z", 949]]