Tutorial by Examples

You can define a new class using the class keyword. class MyClass end Once defined, you can create a new instance using the .new method somevar = MyClass.new # => #<MyClass:0x007fe2b8aa4a18>
A class can have only one constructor, that is a method called initialize. The method is automatically invoked when a new instance of the class is created. class Customer def initialize(name) @name = name.capitalize end end sarah = Customer.new('sarah') sarah.name #=> 'Sarah' ...
There are several special variable types that a class can use for more easily sharing data. Instance variables, preceded by @. They are useful if you want to use the same variable in different methods. class Person def initialize(name, age) my_age = age # local variable, will be destroyed ...
We have three methods: attr_reader: used to allow reading the variable outside the class. attr_writer: used to allow modifying the variable outside the class. attr_accessor: combines both methods. class Cat attr_reader :age # you can read the age but you can never change it attr_writer...
Ruby has three access levels. They are public, private and protected. Methods that follow the private or protected keywords are defined as such. Methods that come before these are implicitly public methods. Public Methods A public method should describe the behavior of the object being created. T...
Classes have 3 types of methods: instance, singleton and class methods. Instance Methods These are methods that can be called from an instance of the class. class Thing def somemethod puts "something" end end foo = Thing.new # create an instance of the class foo.somemeth...
Classes can be created dynamically through the use of Class.new. # create a new class dynamically MyClass = Class.new # instantiate an object of type MyClass my_class = MyClass.new In the above example, a new class is created and assigned to the constant MyClass. This class can be instanti...
In many languages, new instances of a class are created using a special new keyword. In Ruby, new is also used to create instances of a class, but it isn't a keyword; instead, it's a static/class method, no different from any other static/class method. The definition is roughly this: class MyClass ...

Page 1 of 1