Classes in Ruby

Ruby is an object-oriented programming language. This example demonstrates a superclass for representing a car. Two subclasses are used for representing a hero car and a villain car, they inherit from the superclass.

#!/usr/bin/env ruby

class Car

  # Define getters and setters
  attr_accessor :model, :maxSpeed, :fuel

  # Constructor
  def initialize(model, maxSpeed, fuel)
    @model = model
    @maxSpeed = maxSpeed
    @fuel = fuel
  end

  def drive
    puts 'Driving..'
  end
  # Instance to string
  def to_s
    'Model: ' + @model + "\n" +
    'Maximum speed: ' + @maxSpeed + "\n" +
    'Fuel: ' + @fuel
  end

end

# Inheritance

class VillainCar < Car
  def drive
    puts 'Boo!'
  end
end

class HeroCar < Car
  def drive
    puts 'Woo!'
  end
end

carBatman = HeroCar.new("Batmobile","531 km/h","High octane")
carJoker = VillainCar.new("Jokermobile","100 km/h","Helium");

# Display both cars
puts 'Batman drives: '
puts carBatman.to_s + "\n\n"
puts 'The Joker drives: '
puts carJoker.to_s + "\n\n"

# Drive both cars
carBatman.drive
carJoker.drive

Output:

Batman drives:
Model: Batmobile
Maximum speed: 531 km/h
Fuel: High octane

The Joker drives:
Model: Jokermobile
Maximum speed: 100 km/h
Fuel: Helium

Woo!
Boo!

 

This entry was posted in Ruby and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?