Background

Ruby is a scripting language developed by Yukihiro Matsumoto, also known as Matz. It operates on a variety of media, such as Windows, Mac OS, and the different versions of UNIX. Ruby has features that are matching to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is an excellent object-oriented language. Hence, using Ruby syntax is much more comfortable than operating Smalltalk syntax.

Following Image shows ruby language scripting:

Ruby language Script Syntax

 

Why Ruby?

  • Ruby is open-source and is willingly available on the Web, but it is subject to a commission.
  • Ruby is a general-purpose, decoded programming language.
  • Ruby is a real object-oriented programming language.
  • Ruby is a server-side scripting language comparable to Python and PERL.
  • Ruby can be utilized to create Common Gateway Interface (CGI) penmanship.
  • Ruby can be implanted into Hypertext Markup Language (HTML).
  • Ruby has an uncluttered and easy syntax that permits a new designer to learn very fast and easily.
  • Ruby has identical syntax to that of multiple programming languages such as C++ and Perl.
  • Ruby is very much scalable and huge programs written in Ruby are effortlessly maintainable.
  • Ruby can be utilized for developing Internet and intranet applications.
  • Ruby can be installed in Windows and POSIX backgrounds.
  • Ruby backing many GUI tools such as TCL/Tk, GTK, and OpenGL.
  • Ruby can efficiently be linked to DB2, MySQL, Oracle, and Sybase.
  • Ruby has a prosperous set of built-in functions, which can be utilized instantly in Ruby scripts.

Ruby Scripting Syntax API

Ruby is a refined object-oriented language and everything seems to Ruby as an entity. Similarly, every value in Ruby is an entity, even the most elementary things: strings, numbers, and also true and false. Actually, a class itself is an object that is an example of the Class. Moreover, a class is utilized to determine the form of an entity and it incorporates data representation and methods for using that data into one nifty package. The data and methods within a category are called components of the class.

Ruby Class Definition

When you specify a class, you define a blueprint for a data type. This doesn’t define any data, but it does define what the class name depicts, that is, what an entity of the class will consist of and what operations can be operated on such entity or object. Hence, we can define the Box class using the keyword class as follow:

class Box

   code

end

The name must start with a capital letter and by pattern names that consist of more than one word, are run together with per word capitalized and no separating symbols (CamelCase). A class supplies the blueprints for objects, so basically, an object is made from a class. We state objects of a class utilizing a new keyword. The following statements state two objects of class Box.

Box 1 = Box.new

Box 2 = Box.new

The initialize Method

The initialize method is a classic Ruby class process and works the almost same way as constructor functions in other object-oriented programming languages. The initializing procedure is valid when you want to initialize some class variables at the time of object innovation. This method may carry a list of parameters and like any other ruby method, it would be foregone by def keyword as depicted below.

class Box

   def

 initialize (w,h)

      @width, @height = w, h

   end

end

The instance Variables

The instance variables are types of class details and they become properties of objects once objects are made using the class. Every object’s features are assigned separately and shared no matter with other objects. They are reached using the @ operator within the class but to reach them outside of the class we utilize public methods, which are called accessor methods. If we carry the above-defined class Box then @width and @height are representative variables for the class Box.

class Box

   def 

initialize (w,h)

      # assign instance variables

      @width, @height = w, h

   End

end

The Class Methods and Variables

The class variable is a variable, which is transmitted between all models of a class. In other words, there is one model of the variable and it is accessed by object models. Class variables are prefixed with two @ symbols (@@). A class variable must be initialized within the class definition as indicated below.

Moreover, a class method is described using def self.methodname(), which concludes with end delimiter and would be called operating the class name as classname.methodname as displayed in the subsequent example –

#!/usr /bin /ruby -w

class Box

   # Initialize our class variables

   @@count = 0

   def initialize(w,h)

      # assign instance variables

 

      @width, @height = w, h

      @@count += 1

   end

   def self.printCount()

      puts “Box count is : #@@count”

   end

end

# create two object

Box 1 = Box.new (10, 20)

Box 2 = Box.new (30, 100)

Box.printCount(…)

 

When the above code is processed, it produces the following result.

Box count is: 2

Access Control

Ruby offers you 3 levels of security at instance methods status, which may be general, private, or shielded. Ruby does not use any access control over model and class variables.

  1. General Methods − General methods can be reached by anyone. Methods are public by default besides initializing, which is always private.
  2. Private Methods − Private methods cannot be reached, or even viewed from beyond the class. Only the class modes can access private members.
  3. Protected Methods − A shielded method can be summoned only by objects of the descriptive class and its subclasses. Pass is kept within the family.

Class Inheritance

One of the most essential concepts in object-oriented programming is that of inheritance. Inheritance permits us to define a class in words of another class, which forms it easier to create and sustain an application. Similarly, inheritance also delivers an opportunity to reuse the code functionality and quick execution time but unfortunately Ruby does not sustain numerous levels of inheritances but Ruby sustains mixins. A mixin is like a technical implementation of considerable inheritances in which only the interface part is inherited.

When building a class, instead of writing entirely new data members and member positions, the programmer can represent that the new class should inherit the associates of an existing class. This existing class is named the base class or superclass, and the further class is referred to as the derived class or sub-class.

Freezing Objects

Sometimes, we want to avert an object from being changed. The freezing technique in Object allows us to do this, virtually turning an object into a constant. Any object can be frozen by summoning Object.freeze. A frozen object may not be changed: you can’t modify its instance variables. Similarly, you can inspect if a shared object is already frozen or not using Object. frozen? technique, which returns valid in case the object is frozen otherwise a wrong value in return.

Class constants

You can specify a constant inside a class by allocating a direct numeric or string value to a variable, which is assigned without using either @ or @@. By ritual, we keep constant characters in upper case. Once a constant is determined, you cannot modify its value but you can access a constant instantly inside a class greatly like a variable but if you want to access a constant exterior of the class then you would have to operate classname::constant.

Blocks

Ruby has a vision of Block. A block consists of fragments of code. Similarly, you assign a title to a block. The code in the block is usually enclosed within braces ({}). A block is always invoked from an operation with an identical name as that of the block. This identifies that if you have a block with the name test, then you use the function test to conjure this block. Hence, you invoke a block by manipulating the yield message.

block_name {

   statement1

   statement2

   ……….}

 Modules and Mixins

Modules are a way of collecting together methods, classes, and constants. Similarly, they provide you two main benefits; deliver a namespace and control name clashes. Modules execute the mixin establishment. Moreover, modules specify a namespace, a sandbox in which your techniques and constants can play without having to think about being stepped on by other techniques and constants.

module Identifier

   statement1

   statement2

   ………..

end

Module constants are titled just like class constants, with a starting uppercase letter. The method descriptions look similar, too: Module methods are defined just like class methods. As with class methods, you call a module method by prolonging its name with the module’s name and a period, and you refer to a constant using the module name and two colons.

Ruby require Statement

The required statement is identical to the included statement of C and C++ and the import statement of Java. If a 3rd program desires to use any specified module, it can simply pack the module files utilizing the Ruby require statement – require a filename. Here, it is not needed to give.rb extension together with a file name.

Ruby include Statement

You can implant a module in a class. To implant a module in a class, you utilize the include statement in the class – include module name. If a module is programmed in a separate file, then it is needed to include that file using require statement before implanting the module in a class.

Mixins in Ruby

When a class can inherit attributes from additionally one parent class, the class is considered to show considerable inheritance. Ruby does not sustain multiple inheritances presently but Ruby Modules have another amazing use. At a stroke, they pretty much annihilate the requirement for multiple inheritances, providing a facility called a mixin. Mixins give you a wonderfully calm way of adding functionality to classes. However, their actual power arrives when the code in the mixin begins to interact with code in the class that operates it. Let’s understand better by;

module A

   def a1

   end

   def a2

   end

end

 

module B

   def b1

   end

   def b2

   end

end

 

class Sample

include A

include B

   def s1

   end

end

 

samp = Sample.new

 

samp.a1

samp.a2

samp.b1

samp.b2

samp.s1

Module A contains the methods a1 and a2. Module B contains the methods b1 and b2. The class Sample includes two of those modules A and B. The class Sample can reach all 4 methods, namely, a1, a2, b1, and b2. so, you can see that the class Sample inherits from each of the modules. Thus, you can now say the class Sample represents different inheritance or a mixin.

Variables

Variables are the memory locations, which carry any data to be operated by any program. There are 5 types of variables backed by Ruby.

Ruby Global Variables

Global variables initiate with $. Uninitialized global variables hold the value nil and deliver warnings with the -w alternative. Assignment to global variables changes the global status. It is not advised to operate global variables. They make operations cryptic.

Ruby Instance Variables

Instance variables start with @. Uninitialized sample variables have the value nil and deliver warnings with the -w alternative.

Ruby Class Variables

Class variables start with @ and should be initialized before they can be utilized in method descriptions. Similarly, referencing an uninitialized class variable produces an error. Class variables are made mutual among descendants of the class or module in which the class variables are described. 

Ruby Class Variable Script syntax

Ruby Local Variables

Local variables start with a lowercase letter or _. The extent of a local variable varies from class, module, def, or do to the interconnected end or from a block’s beginning brace to its close brace {}. Similarly, when an uninitialized regional variable is referenced, it is interpreted as visitation to a method that has no assertions. Assignment to uninitialized regional variables also acts as a variable mandate. Moreover, the variables start to exist until the rear of the current content is reached. The lifetime of local variables is demarcated when Ruby parses the schedule.

Ruby Local Variable Script Syntax Example

 Ruby Constants

Ruby Constants within a class

Constants start with an uppercase letter. Constants described within a class or module can be reached from within that class or module, and those described outside a class or module can be reached globally. Similarly, constants may not be defined within methods. Referencing an uninitialized constant yield a fallacy. Therefore, assembling an assignment to a constant that is already initialized creates a warning.

Related Tutorials on Ruby links

Ruby Tutorial For Complete Beginners: Learn Ruby Now!

Learn Ruby: 30 Best Ruby Tutorials for Programmers – Stackify

Learn Ruby in Twenty Minutes

Ruby Tutorial: Learn Ruby For Free

Learn Ruby Tutorial – javatpoint

Ruby Tutorial – GeeksforGeeks

Ruby Tutorial – Tutorialspoint

About Learningcomputer.com

Learningcomputer.com is a free training website. We provide Information Technology training and distance learning. We have FREE computer training on products like Microsoft Windows, Microsoft Office, Microsoft Word, Microsoft Excel, Mozilla Firefox, Microsoft PowerPoint, Microsoft Access, Visual Basic, Internet Explorer, Java, SQL Server, eBay, and many more topics on IT training and computer learning.

About the Author

This article was written and Optimized by Omar A. Malik. He’s an SEO Content Specialist and a Web Developer. Visit LinkedIn profile for more details. Omar A. Malik