Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 9 / 68

Classes (Object-Oriented Programming)

In this lesson you will learn the basics of object-oriented programming with Ruby's class syntax, so you can group data that shares the same characteristics. This is for anyone searching for "Ruby class how to use".

class ... end defines a class. initialize is the special method used for initialisation, and variables starting with @ are instance variables. Think of it as an "animal blueprint" from which you can create as many concrete instances as you like.

The sample code gives the Animal class the instance variables @name and @sound, and builds a message in the speak method. Notice how dog.speak is called on the instance created with Animal.new("Dog", "Woof").

A common stumbling block for beginners is the difference between an @ variable and an ordinary one. An instance variable starting with @ keeps its value for as long as the object exists - a fundamental of object orientation - while an ordinary variable disappears when the method ends.

The attr_accessor mechanism conveniently generates getters and setters for you. It is used constantly in real Ruby code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)