From: "David A. Black" Date: 2009-07-21T22:27:11+09:00 Subject: Re: Mean method --1926193751-335273915-1248182817=:10256 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-335273915-1248182817=:10256" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-335273915-1248182817=:10256 Content-Type: TEXT/PLAIN; charset=utf-8; format=flowed Content-Transfer-Encoding: 8BIT Hi -- On Tue, 21 Jul 2009, Älphä Blüë wrote: > I'm working on a lot of math in my projects so I thought I would convert > over a few methods I used in other languages that I created and port > them to ruby. > > Here's a mean method which allows you to return either: > > a) arithmetic mean > b) geometric mean > c) harmonic mean > > http://pastie.org/553287 > > Enjoy. Thanks for sharing the code. I've got a few suggestions for refactoring it, which I hope you won't mind my sharing with you. First of all, if you want to call #sum on an array, you'll need a #sum method :-) I've thrown in #product too. class Array def sum inject {|a,b| a + b } end def product inject {|a,b| a * b } end end And here's a somewhat more concise version of your mean method. Note that I don't check the classes of the arguments. I'd rather try to make them work, and if they don't then an exception will be raised at some point anyway. I do, however, add a check to make sure the mean type is a known one. def mean(array, i_type = 1) case i_type when 1 then array.sum / array.size when 2 then array.product ** (1.0/array.size) when 3 then array.size / array.inject {|a,b| a + 1.0 / b } else raise ArgumentError, "Unknown mean type '#{i_type}'" end end It might be user-friendly to wrap the various types in methods of their own: def arithmetic_mean(array) mean(array, 1) end etc. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) Training! Intro to Ruby, with Black & Kastner, September 14-17 (More info: http://rubyurl.com/vmzN) --1926193751-335273915-1248182817=:10256-- --1926193751-335273915-1248182817=:10256--