class LineAnalyzer
@@highest_wf_count = 0
@@highest_wf_words = Array.new
def highest_wf_count
@@highest_wf_count
end
def higest_wf_words
@@highest_wf_words
end
attr_accessor :linesCount, :content , :line_number
@content
@line_number
def initialize(line,line_count)
@content = line
@line_number = line_count
#* call the calculate_word_frequency() method.
calculate_word_frequency()
end
def calculate_word_frequency()
@@count = Hash.new(0)
@content.split.each do |word|
@@count[word.downcase] += 1
end
@@count.each_pair do |key, value|
if value > @@highest_wf_count
@@highest_wf_count = value
end
end
@@count.each_pair do |key, value|
if value == @@highest_wf_count
@@highest_wf_words << key
end
end
end
end
# Implement a class called Solution.
class Solution
attr_accessor :highest_count_across_lines, :highest_count_words_across_lines
@highest_count_across_lines = 0
@highest_count_words_across_lines = Array.new()
@@LineAnalyzers = Array.new
def analyze_file
line_count = 1
x = File.foreach('C:\x\test.txt')
x.each{ |line|
@@LineAnalyzers << LineAnalyzer.new(line , line_count)
line_count+=1
}
puts @@LineAnalyzers.inspect
end
def calculate_line_with_highest_frequency
@@LineAnalyzers.map { |line|
#Here is the problem.... I need to assign values to @highest_counts_across_lines and @highest_count_words_across_lines
}
end
end
我的问题是我有这个LineAnalyzers数组,我有最高_wf_count和highest_wf_words,我想将它们分配给@higest_count_across_lines和@highest_count_accross_words,我不知道如何在循环时访问LineAnalyzer属性解决方案类
答案 0 :(得分:0)
这是Sergio Tulentsev解决的简短答案
word_freq = File.new(filename, 'r').each_with_object(Hash.new(0)) do |line, memo|
line.split.each {|word| memo[word] += 1 }
end
max = word_freq.values.max
most_frequent_words = word_freq.select {|k, v| v == max }.map[0]