Model a motorcycle
Monday Jun 15, 2015
Classes in programming represent real world objects. the best place to use a class is when you anticipate repeatedly make a certain object. For example lets image that we want to create a program which creates motorcycle. Assuming that our program already has knowledge of a vehicle class, which covers having wheels and steering and traveling we can focus on the particulars of a motorcycle. our class may look something like this:
class Motorcycle
def initialize(brand, cc, positions)
unless ["Yamaha", "Honda", "Suzuki", "Kawasaki"].include?(brand)
raise ArgumentError.new("#{brand} is not a Japanese Motorcycle manufacturer")
end
unless cc.to_i.between?(50, 2300)
raise ArgumentError.new("#{cc} is not within the range of motorcycle engine size")
end
unless ["upright", "sport", "cruiser"].include?(positions)
raise ArgumentError.new("#{positions} is not a riding style")
end
@brand = brand
@engine = cc
@style = positions
end
def info
if @cc > 600
puts "The motorcycle is a #{@brand}, #{@engine}cc #{@style}. It sounds fast!"
else
puts "The motorcycle is a #{@brand}, #{@engine}cc #{@style}. you must be a beginner."
end
end
my_bike = Motorcycle.new("Yamaha", "850", "upright")
my_bike.info
Although this class current only implentents 2 methods you can theoritically create an infinite number of methods that corrispond to a motorcycle like color or wheel base, if it has saddlebags, etc.. and these methods will be avaliable for every object of class Motorcycle.