I've just finished exercise #1 from: knowing.net. Please feel free to critique this code, I am serious about learning Ruby and getting introduced to members of the community.
proj1.rb
# Write a program that takes as its arguments one of the words ’sum’, # ‘product’, ‘mean’, or ’sqrt’ followed by a series of numbers. The # program applies the appropriate function to the series. # the mathn library makes the Math.sqrt call below behave better in # situations involving negative sums. require 'mathn' class Array def sum # missed the inject method on my first # skim of the 'Programming Ruby' appendix. self.inject {|sum, i| sum + i}.to_f end def product self.inject(1) {|product, i| product * i}.to_f end def mean self.sum / self.size end def sqrt Math.sqrt(self.sum) end end raise "usage: ruby proj1.rb {sum|product|mean|sqrt} {value}+" if ARGV.size < 2 Allowed_commands = ["sum", "product", "mean", "sqrt"] command = ARGV.shift.downcase raise "unknown command: #{command}" unless Allowed_commands.include? command # I don't like this line, is there a better # way to do String -> numeric conversions? ARGV.collect! {|i| i.to_f} puts eval ARGV.to_s + "." + command
Comments