Ruby - SPLessons

Ruby Classes and Objects

Home > Lesson > Chapter 4
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Ruby Classes and Objects

Ruby Classes and Objects

shape Introduction

This chapter demonstrates about the Ruby Classes, the Object class is the blue print in which user can create the individual objects, following are the concepts are covered in this chapter.
  • Classes in Ruby
  • Objects in Ruby

Classes in Ruby

shape Description

Ruby is also known as pure Object Oriented Programming Language which involves some classes and objects. Class definitions start with class keyword and ends with end keyword. Generally the end keyword is used to finish all blocks of code. In a class variable names must begin with a lowercase letter and class names begin with an uppercase letter. Multiple words and class names are delineated using CamelCase and acronyms are normally written in uppercase letters. classes in Ruby as shown below. [ruby] class Customer end [/ruby] Ruby Class Variables In a Ruby class Variables are divided into four types as listed below.

Objects in Ruby

shape Description

In Ruby Classes and Objects, Objects are instances of the class. User can create the objects in Ruby by using the new method of the class which is the unique type of method and is predefined by the Ruby Library. By using custom methods also user can create the Ruby Objects by passing the parameters to the initialize class variables, if user want to declare new method with his parameters can define initialize at the time of class creation. Initialize method will execute when another new method of the class is get invoked with parameters. In ruby functions are also known as members each method starts with key word and followed by method name the code below demonstrates creating the one object of same class with hello method as shown below. [ruby] class Sample def hello puts "Hello Ruby!" end end # Now using above class to create objects object = Sample. new object.hello [/ruby] Result By running the above code in command prompt, the output can be obtained as shown in the image below.

Summary

shape Key Points

  • Ruby Classes and Objects are Instances of class.
  • Ruby Classes and Objects - Ruby is Objected Oriented Programming Language.
  • Ruby Classes and Objects Class name starts with upper case letter.