2014-02-18 23 views
0

所以我被告知要重寫這個問題並概述我的目標。他們讓我遍歷數組,並且「使用.each遍歷頻率並將每個單詞和它的頻率打印到控制檯上......爲了可讀性在單詞和它的頻率之間放置一個空格。」如何通過遍歷Ruby中的數組來創建直方圖

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 

爲什麼不能將字符串轉換爲整數?我做錯了什麼?

回答

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)$ 
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. 
+0

爲什麼'reverse'和'sort_by'需要? :-) –

+0

@ArupRakshit:刪除,謝謝。 – Linuxios

+0

非常感謝Linuxios。這工作。我必須回去看看我做錯了什麼。我們還沒有學習.uniq方法,但它看起來就是這麼做的,所以我會查找它,以便我可以在將來自行使用它。 – user3324987

0

是一個很好的方法。它返回一個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]]