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

时间:2014-02-18 22:08:31

标签: ruby arrays histogram

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

puts "Type something profound please"
text = gets.chomp
words = text.split

frequencies = Hash.new 0
frequencies = frequencies.sort_by {|x,y| y}
words.each {|word| frequencies[word] += 1}
frequencies = frequencies.sort_by{|x,y| y}.reverse
puts word +" " + frequencies.to_s
frequencies.each do |word, frequencies|   

end

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

3 个答案:

答案 0 :(得分:0)

我会这样做:

puts "Type something profound please"
text = gets.chomp.split

我在这里打电话给Enumerable#each_with_object方法。

hash = text.each_with_object(Hash.new(0)) do |word,freq_hsh|
  freq_hsh[word] += 1
end

我调用了Hash#each方法。

hash.each do |word,freq|
  puts "#{word} has a freuency count #{freq}"
end

现在运行代码:

(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)$ 

答案 1 :(得分:0)

试试这段代码:

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.

答案 2 :(得分:0)

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]]