Ruby: Classes and Objects
Classes and Objects
Defining a class. Class name should start with a capital letter.
# ruby # Object example class Xyz # initializer def initialize(ii) @xx = ii # @xx is a instance variable end # a method. Return the instance variable @xx def mm @xx end # a another method. def nn(aa) @xx + aa end end # create a object. myobj = Xyz.new(3) # call a method p myobj.mm # 3 # call another method with argument p myobj.nn(2) # 5
Instance variable must be accessed by methods only. You must define methods to get instance variable's value, or change it. (this is different from Java or Python.)
- “Instance Variable” are variables such that each object has a different copy. Changing one variable in one object doesn't change that variable's value in another object. Name of instance variables must start with
@
. - “Class Variable” are variables such that all objects share one single copy of the variable. Name of class variables must start with
@@
.