Object Oriented Programming

Class Declaration & Structure in Ruby

Classes are a blueprint for creating individual objects that contain the general characteristics of a defined object type.


Syntax
class className 
    #fields, constructor

    #method declarations

    private
    #everything here and below will only be accessible within the class
end

Notes

The class body contains constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behaviour of the class and its objects.


Example
class Bike
    #Constructor: 
    def initialize(gear, speed) 
        @gear = gear; 
        @speed = speed; 
     end
     
    def applyBrake(decrement)
        @speed -= decrement; 
    end

    def speedUp(increment)  
        @speed += increment; 
    end 

    private
    #visible only within the class
    def changeGears(newGears)
        @gears = newGears
    end
end

See Also
Documentation

Class - Ruby API

Add to Slack

< Lambda   |   Class and Instance Variables >

© 2019 SyntaxDB. All Rights Reserved.