Ruby: Classes and Objects

By Xah Lee. Date: .

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.)