2014-02-18 3 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

왜 '역행'과 '정렬'이 필요합니까? :-) –

+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]] 
관련 문제