It gives you the choice of calculating the area of a circle, rectangle, or triangle:
Code:
#!/usr/bin/env ruby
# The Area Calculator
# Calculate the area of a variety of shapes
def circle()
# Get radius
print "Radius: "
radius = STDIN.gets
radius = Float(radius.chop!)
# Calculate area and print it
area = 3.14 * radius * radius
print "The area is ", area, "\n"
exit
end
def rectangle()
# Get base and height
print "Base: "
base = STDIN.gets
base = Float(base.chop!)
print "Height: "
height = STDIN.gets
height = Float(height.chop!)
# Calculate area and print it
area = base * height
print "The area is ", area, "\n"
exit
end
def triangle()
# Get base and height
print "Base: "
base = STDIN.gets
base = Float(base.chop!)
print "Height: "
height = STDIN.gets
height = Float(height.chop!)
# Calculate the area and print it
area = (base * height) / 2
print "The area is ", area, "\n"
exit
end
# Start the script
print "Area Calculator!\n\n"
print "Select a shape:\n"
print "1 Circle\n"
print "2 Rectangle\n"
print "3 Triangle\n\n"
print "? "
# Get input - Which shape?
choice = STDIN.gets
# Catch exceptions when input is String or Float - exit
begin
choice = Integer(choice.chop!)
rescue
print "Invalid selection\n"
exit
end
print "\n"
# Calculate the area of the selection
# Catch exceptions when input in area calculations
# is String
begin
case choice
when 1
circle()
when 2
rectangle()
when 3
triangle()
end
rescue
end
# This is reached when an exception occurs above
# or when choice does not equal 1, 2, or 3
# Otherwise, the shape functions exit after area calculation
print "Invalid Selection\n"
What do you think? A little sloppy? Should I add more shapes? 
By the way, is there a default statement in Ruby (for the case statement)? And does anyone know of any good Ruby tutorials? I found like two of them, and they aren't very... super.
Bookmarks