For a basic program, classes are completely useless. For a beginner programmer they just add extra complexity.
The larger and more complex a program becomes, the harder it is to find good names for all the methods. Classes help. Classes also allow grouping of similar types of code together to make the whole program easier to work with.
There are more reasons for classes, but that's outside of the scope of this basic introduction.
Defining a class ∞
The first letter must be capitalized, because it is a 'constant'.
class Example_class end
Initializing a class ∞
Every class must contain a method called 'initialize'.
class Example_class def initialize end end
Within our regular Ruby code, new objects can be created which use Example_class:
example_object = Example_class.new
That '.new' executes the 'initialize' method within our class.
No output is displayed because that class and its initialize method don't return information or output text. We could do something like this:
class Example_class def initialize puts "Hello, World!" end end foo = Example_class.new # => # Hello, World!
Returning data ∞
Variables within classes begin with an at ( @ ).
Methods can be created inside the class. They are used with
class Example_class def initialize @var1 = "Hello, World!" @var2 = "Hi!" end def var1 return @var1 end def var2 return @var2 end end example_object = Example_class.new puts example_object.var1 # => # Hello, World! a = example_object.var2 puts a # => # Hi!
Receiving and returning data ∞
Classes work just like methods do. They can receive, process and return data.
To do that, you create methods within the class which look and work exactly like methods at the "top level" of Ruby.
class Example_class def initialize end def hello_message(message) puts "You asked me to output: " + message end end example_object = Example_class.new example_object.hello_message("some text") # => # You asked me to output: some text