The Car Goes Vrooooom!

Howdy Howdy Friends,

Today I am taking a few minutes to describe and explain a simple assignment that I completed with ruby.

The assignment reads as follows:

Using the following data, calculate and print out the average miles per gallon for each vehicle. Round the output to the nearest 10th gallon. Be sure to use variables with easily recognizable names.

The Data

Vehicle Miles Gallons
1970 VW Bug 286 9
1979 Firebird 412 40
1980 Subaru 361 18
1975 Cutlass 161 11

So now that we have our data, we should go ahead and model it with a class.

class Car
# Our car has some attributes, let's define them
attr_accessor :miles, :gallons, :model

# Lets setup our initializer. The initialize method is run before each new instance of the class Car
def initialize(model, miles, gallons)
  # here we set the instance attributes
  @model = model; @miles = miles; @gallons = gallons
end

# Now, let's calculate miles per gallon
def miles_per_gallon
  sprintf("%#1.1f", (miles.to_f / gallons.to_f))
end
end

# Now, let's instantiate our cars! VROOOOOM!
@volkswagon = Car.new("1970 VW Bug", 286, 9)
@firebird   = Car.new("1979 Firebird", 412, 40)
@subaru     = Car.new("1980 Subaru", 361, 18)
@cutlass    = Car.new("1975 Cutlass", 161, 11)

# We should but those cars into an array so we can iterate through each of them
cars = [@volkswagon, @firebird, @subaru, @cutlass]

# Begin our assigned output
puts “Kansas City Grand Prix”
puts “Miles/Per Gallon”
puts “”
cars.each do |car|
  puts “#{car.model} averaged #{car.miles_per_gallon} m/g”
end

Great! And when we run that, this is the output:

Kansas City Grand Prix
Miles/Per Gallon

1970 VW Bug averaged 31.8 m/g
1979 Firebird averaged 10.3 m/g
1980 Subaru averaged 20.1 m/g
1975 Cutlass averaged 14.6 m/g

This was an easy assignment, really. The only true black box method for me is the sprintf() or format() method.
I’ll try to explain what that method actually does.

# Say we wanted to format PI to show the decimals only to the hundreds place... I'll use format(). You can use sprintf(). They are the same
format("%#1.3f", Math::PI)

You can read all about the sprintf method here: http://www.ruby-doc.org/core/classes/Kernel.html#M001094

Have a better way of doing this? Tell me all about it! Leave a comment.