Hello,This is my solution to the Sentence length solution on the StartProblemspage of the RubyGarden wiki.
I learned a few things from doing this simple exercise and I wasjust wondering if anyone would be willing to help me refactor thecode as a further learning exercise.
I'm not looking for a new solution, I just want to make this existingsolution better, andimprove the OO of the code.
You can post replys to this email, or you can post replyson my blog, where I also have this posted.Either will be very appreciated!
class Evaluator def initialize(file) @reg = [] @char = "" File.open(file, 'r') do |f| f.each do |line| @char << line end end split_and_strip(@char) end
#split every sentence, then strip the newline characters. def split_and_strip(str) str.split(/[.?!]\s*/).each do |x| @reg << x.gsub("\n", " ") end end
def average? @char = @reg.inject(0) do |m,o| m + o.length end print "\nThe average sentence is ", (@char / @reg.length), "characters long." end
def biggest? @char = @reg.inject(@reg[0].length) do |m,o| if m >= o.length m else o.length end end print "\nThe biggest sentence is ", (@char), " characters long." end
def smallest? @char = @reg.inject(@reg[0].length) do |m,o| if m <= o.length m else o.length end end print "\nThe smallest sentence is ", (@char), " characters long." endend
e = Evaluator.new("words.txt")e.smallest?e.average?e.biggest?
--Alex Combashttp://noodlejunkie.blogspot.com/