Skip to main content

Learning Ruby: Knowing.net Exercise #1

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

Popular posts from this blog

Using MonoDevelop to Create an ASP.NET Web Service

NOTE : instructions below are for MonoDevelop 2.6 Beta 2 - built on 2011-04-06 03:37:58+0000 Getting Started Create a new ASP.NET Web Application in MonoDevelop: From the menu, select: File → New → Solution… Expand C# . Select ASP.NET → Web Application . Enter a name for the ASP.NET project that will be created in the solution in Name: . Change the root location for the solution in Location: , if desired. Change the name of the root solution in Solution Name: , if desired. The Results – I What you have after executing the new ASP.NET Web Application project wizard is a solution containing one ASP.NET Web Application project. In the default project view in MonoDevelop, you'll find the following items: Default.aspx – This is the default web form rendered and presented in the browser when http://<server>:<port>/ is accessed. Default.aspx.cs – This C# file contains the developer-created common code and event handlers whic...

Maven note: exec-maven-plugin

I'm currently working on a development package containing a series of .xsd files which will be used to define the external interface for our web service. Due to some other project constraints, it was decided that this package also needed to include the .wsdl files which will further define the web service.