Ruby Tutorial

Ruby is a object-oriented, reflective, general-purpose, dynamic programming language. Ruby was developed to make it act as a sensible buffer between human programmers and the underlying computing machinery. It is an interpreted scripting language which means most of its implementations execute instructions directly and freely, without previously compiling a program into machine-language instructions. Ruby is used to create web applications of different sorts. It is one of the hot technology at present to create web applications.

Topics:

 

Features of Ruby

Ruby has many reasons for being popular and in demand. Few of the reasons are mentioned below:

  1. The code written in Ruby is small, elegant and powerful as it has fewer number of lines of code.
  2. Ruby allows simple and fast creation of Web application which results in less hard work.
  3. As Ruby is free of charge that is Ruby is free to copy, use, modify, it allow programmers to make necessary changes as and when required.
  4. Ruby is a dynamic programming language due to which there is no tough rules on how to built in features and it is very close to spoken languages.

Application Areas

Getting Started with Ruby

Ruby is an interpreted, high-level, general-purpose programming language. Ruby is dynamically typed and uses garbage collection. It supports multiple programming paradigms, object-oriented, including procedural and functional programming. Ruby is based on many other languages like Perl, Lisp, Smalltalk, Eiffel and Ada. This language has an elegant syntax that is natural to read and easy to write. Popular Ruby Editors/IDE are below.

  • Notepad/gedit : They are simple text-editor for writing ruby programs. Notepad is available on Windows and gedit is available on Linux.
  • NetBeans : It is a well known free IDE(Integrated Development Environment) for developing softwares in ruby. we can download NetBeans from here.
  • .

Downloading and Installing Ruby In window:

  1. We can download Ruby from rubyInstaller.org Click on any link as your preferred version depending on our Windows for say we can go with WITHOUT DEVKIT versions like Ruby 2.6.4-1 (x64) for Windows(64 bit) and the 2nd link which says Ruby 2.6.4-1 (x86) is for Windows(32 bit) as highlighted below, which is the latest version.
  2. null

  3. After downloading the file, run the .exe file and follow the instructions to install Ruby on your Windows. Once you installed Ruby with default settings on your Windows, you have to setup environment variable.
  4. Go to Control Panel -> System and Security -> System.
    Then click on Advanced System Setting option then under Advanced tab click on Environment Variables.
  5. Now, we have to Edit the “Path” variable under System variables so that it also contains the path to the Ruby environment. Under the System Variable select the “Path” variable and click on Edit button.
  6. We will see list of different paths, click on New button and then add path where Ruby is installed. By default, Ruby is installed in “C:\Ruby26-x64\bin” (in our case) folder OR “C:\Ruby26-x86\bin”. In case, you have installed Ruby at any other location, then add that in path, for example: if you have installed Ruby on other drive then go to that driver and locate the Ruby folder then inside the ruby folder a folder called bin will be there so copy the path and include it to System Variable’s Path like SomeDrive:\SomeFolder\RubyXX-xYY\bin
  7. Click on OK, Save the settings and we are done. Now to check whether installation is done correctly, open command prompt and type ruby -v and hit Enter. You will see some output like ruby 2.6.4p104 (2019-08-28 revision 67798) [x64-mingw32](in our case) on the console. It means we have successfully installed Ruby and we are good to go.

Downloading and Installing Ruby In Linux

  1. Go to Application -> Terminal
  2. Type command as below.
    sudo apt install ruby-full

    and press enter and enter your password. Wait for it to complete the download and then it will install Ruby on your machine.

  3. We are done installing Ruby on Linux. Now to check whether installation is done correctly, type ruby -v in the Terminal.If you see some text like ruby 2.6… it means u have successfully installed Ruby on your Linux.

How to Run a Ruby Program ?

  • With Online IDE :
    Let’s consider a simple Hello World Program.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    puts "Hello World"

    chevron_right

    
    

    Output :

    Hello World

    Above code will run on online IDE. Here, puts keyword is used to print any thing on the screen.

  • With Linux :
    Using Command-Line Firstly, open a text editor Notepad or Notepad++. write the code in the text editor and save the file with (.rb) extension. open the command prompt follow step by step process on our system.



    To run the hello.rb Ruby script, run the command ruby hello.rb it will print the output.

  • With Window :
    Using Command-Line write ruby -v on command line window to show ruby version. Below is the image to better understand.

    To start the IRB prompt, open your command-line and run the irb command. after this we can write the ruby code and it will run on command line.

    In above image we use puts keyword to print the output and it returned nil.
  • Fundamentals of Ruby

    Variables

    A variable in simple terms is a storage place which has some memory allocated to it. Basically, a variable used to store some form of data. Variables are simply a storage location. Every variable is known by its name and stores some known and unknown piece of information known as value. There are different types of variables in Ruby:

    • Local variables
    • Instance variables
    • Class variables
    • Global variables

    Example:

    # Local Variable
    age = 10
    _Age = 20
    
    # Global variable 
    $age = 10
    
    # Instance Variables      
    @age = 20 
    
    # Class Variables 
    @@age = 20
    

    To know more about Variables, please refer to Variables in Ruby

    Decision Making

    Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. in Ruby, the if-else statement is used to test the specified condition. There are various ‘if’ statements in Ruby:

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate 
    # Decision-Making statements
      
    a = 10
    b = 15;
      
    # if condition to check 
    # for even number 
    if a % 2 == 0  
         puts "Even Number" 
    end
      
    # if-else condition to check 
    # for even number or odd number
    if b % 2 == 0  
        puts "Even Number" 
    else
        puts "Odd Number" 
    end 

    chevron_right

    
    

    Output :

    Even Number
    Odd Number

    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate the  
    # if-else-if or Ternary statement 
    a = 78  
    if a  < 50   
      puts "Student is failed"  
         
    elsif a >= 50 && a <= 60   
      puts "Student gets D grade"  
         
    elsif a >= 70 && a <= 80   
      puts "Student gets B grade" 
          
    elsif a >= 80 && a <= 90   
      puts "Student gets A grade" 
           
    elsif a >= 90 && a <= 100   
      puts "Student gets A+ grade"    
    end
      
    # ternary statement 
    b = (a > 2) ? true : false
    puts b 

    chevron_right

    
    

    Output :

    Student gets B grade
    true

    To know more about decision making please refer to Decision Making In Ruby.

    Blocks

    A block is the same thing as a method, but it does not belong to an object. Blocks are called closures in other programming languages. In ruby, Block can accept arguments and returns a value. A block is always invoked with a function or can say passed to a method call. To call a block within a method with a value, yield statement is used.
    A block code can be used in two ways as follows:
    Inside the do..end statement
    Example :



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the block 
    # defined inside do..end statements 
        
    # here 'each' is the method name  
    # or block name  
    # n is the variable 
    ["Geeks", "GFG", 55].each do |n|    
     puts n    
    end   

    chevron_right

    
    

    Output :

    Geeks
    GFG
    55

    Inline between the curly braces {}
    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the block 
    # Inline between the curly braces {} 
        
    # here 'each' is the method name  
    # n is the variable 
    ["Geeks", "GFG", 55].each {|i| puts i}   

    chevron_right

    
    

    Output :

    Geeks
    GFG
    55
    

    The yield Statement

    The yield statement is used to call a block inside the method using the yield keyword with a value.
    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the yield statement 
        
    # method 
    def GFG
            
      # statement of the method to be executed 
      puts "Inside Method!"
          
        # using yield statement 
        yield
            
      # statement of the method to be executed  
      puts "Again Inside Method!"
          
      # using yield statement 
      yield
          
    end
        
    # block 
    shivi{puts "Inside Block!"

    chevron_right

    
    

    Output :

    Inside Method!
    Inside Block!
    Again Inside Method!
    Inside Block!

    the block will execute it gives control back to the method and the method will continue to execute from where yield statement called.

    BEGIN and END Block
    Ruby source file has a feature to declare the block of code which can run as the file is being loaded i.e the BEGIN block. After the complete execution of the program END block will execute.

    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the BEGIN and END block 
        
    #!/usr/bin/ruby 
        
    # BEGIN block 
    BEGIN {  
            
       # BEGIN block code  
       puts "This is BEGIN block Code"
    }  
        
    # END block  
    END {  
            
       # END block code  
       puts "This is END block code"
        
    # Code will execute before END block  
    puts "Before END block"

    chevron_right

    
    

    Output :



    This is BEGIN block Code
    Before END block
    This is END block code

    To know more about Blocks, please refer to Blocks in Ruby

    Loops

    Looping in programming languages is a feature which clears the way for the execution of a set of instructions or functions repeatedly when some of the condition evaluates to true or false. Ruby provides the different types of loop to handle the condition based situation in the program to make the programmers task simpler. The loops in Ruby are :

    • for loop
      Example :

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      # Ruby program to illustrate 'for'  
      # loop using range as expression 
          
      i = "Sudo Placements"
          
      # using for loop with the range 
      for a in 1..5 do
              
       puts i 
           
      end

      chevron_right

      
      

      Output:

      Sudo Placements
      Sudo Placements
      Sudo Placements
      Sudo Placements
      Sudo Placements
      
    • while loop
      Example :

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      # Ruby program to illustrate 'while' loop 
          
      # variable x 
      x = 4
          
      # using while loop  
      # here condtional is x i.e. 4 
      while x >= 1 
          
      # statements to be executed 
        puts "GeeksforGeeks"
        x = x - 1
            
      # while loop ends here 
      end

      chevron_right

      
      

      Output:

      GeeksforGeeks
      GeeksforGeeks
      GeeksforGeeks
      GeeksforGeeks
      
    • do..while loop
      Example :

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      # Ruby program to illustrate 'do..while'loop 
          
      # starting of do..while loop 
      loop do
              
       puts "GeeksforGeeks"
           
       val = '7'
           
       # using boolean expressions 
       if val == '7'
        break
       end
           
      # ending of ruby do..while loop  
      end 

      chevron_right

      
      

      Output:

      GeeksforGeeks
      
    • until loop
      Example :

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      # Ruby program to illustrate 'until' loop 
          
      var = 7
          
      # using until loop 
      # here do is optional 
      until var == 11 do
          
        # code to be executed 
        puts var * 10
        var = var + 1
            
      # here loop ends 
      end

      chevron_right

      
      

      Output :



      70
      80
      90
      100

    To know more about Loops please refer to Loops in Ruby

    Ruby Method

    Method is a collection of statements that perform some specific task and return the result. Methods allow the user to reuse the code without retyping the code. Methods are time savers and help the user to reuse the code without retyping the code. In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword.
    Syntax :

    def method_name
    # Statement 1
    # Statement 2
    .
    .
    end

    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate the defining  
    # and calling of method 
        
    #!/usr/bin/ruby 
        
    # Here geeks is the method name 
    def geeks 
        
    # statements to be displayed 
    puts "Welcome to GFG portal"
        
    # keyword to end method 
    end
        
    # calling of the method 
    geeks 

    chevron_right

    
    

    Output :

    Welcome to GFG portal

    To know more about Method please refer to Ruby Method

    OOPs Concepts

    When we say object-oriented programming, we mean that our code is centered on objects. Objects are real-life instances that are classified into various types. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. Ruby supports the OOP paradigm by allowing the creation of classes and its objects.
    OOPs Concepts:

    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate  
    # the class and object and Inheritance 
        
    #!/usr/bin/ruby  
        
    # Super class or parent class 
    class GeeksforGeeks  
        
        # constructor of super class 
        def initialize  
                
            puts "This is Superclass"
        end
            
        # method of the superclass 
        def super_method 
                
            puts "Method of superclass"
        end
    end
        
    # subclass or derived class  
    class Sudo_Placement < GeeksforGeeks  
        
        # constructor of deriver class 
        def initialize  
        
           puts "This is Subclass"
        end
    end
        
    # creating object of superclass 
    GeeksforGeeks.new
        
    # creating object of subclass 
    sub_obj = Sudo_Placement.new
        
    # calling the method of super  
    # class using sub class object 
    sub_obj.super_method 

    chevron_right

    
    

    Output :

    This is Superclass
    This is Subclass
    Method of superclass

    To know more about OOPS please refer to Ruby OOP’s set 1 and set 2

    Ruby Module

    A Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword not with class keyword. Modules are used as namespaces and as mixins. In Ruby, The name of a module must start with a capital letter.
    Syntax :



    module Module_name
    
       # statements to be executed
    
    end
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate  
    # the module 
          
    # Creating a module with name Gfg 
    module Gfg 
            
        C = 10
          
        # Prefix with name of Module 
        # module method  
        def Gfg.portal 
            puts "Welcome to GFG Portal!"
        end
              
        # Prefix with the name of Module 
        # module method 
        def Gfg.tutorial   
            puts "Ruby Tutorial!"
        end
              
        # Prefix with the name of Module 
        # module method 
        def Gfg.topic   
            puts "Topic - Module"
        end
            
    end
         
    # displaying the value of  
    # module constant 
    puts Gfg::C
        
    # calling the methods of the module 
    Gfg.portal 
    Gfg.tutorial 
    Gfg.topic 

    chevron_right

    
    

    Output:

    10
    Welcome to GFG Portal!
    Ruby Tutorial!
    Topic - Module

    To know more about Ruby Module please refer to Ruby Module

    Exceptions

    A good program(or programmer) predict error and arrange to handle them in an effective manner. This is not as easy as it sounds. Exceptions are the errors that occur at runtime. An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the program’s instructions.
    It is the package that contains the information about the exception in an object. Ruby contains a predefined hierarchy of exceptions as shown below:

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to create the user  
    # defined exception and rescued  
        
    # defining a method 
    def raise_and_rescue      
      begin 
              
        puts 'This is Before Exception Arise!'
              
        # using raise to create an exception   
        raise 'Exception Created!'
        
        puts 'After Exception'  
        
      # using Rescue method 
      rescue     
        puts 'Finally Saved!'     
          
    end     
        
    puts 'Outside from Begin Block!'     
        
    end     
        
    # calling method 
    raise_and_rescue  

    chevron_right

    
    

    Output :

    This is Before Exception Arise!
    Finally Saved!
    Outside from Begin Block!

    To know more about Exceptions please refer to Ruby Exception

    Regular Expression

    A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing. Ruby regex can be used to validate an email address and an IP address too. Ruby regex expressions are declared between two forward slashes.
    Syntax :

    # finding the word 'hi'
    "Hi there, i am using gfg" =~ /hi/

    This will return the index of first occurrence of the word ‘hi’ if present, or else will return ‘ nil ‘.
    Checking if a string has some set of characters or not
    We can use a character class which lets us define a range of characters for the match. For example, if we want to search for vowel, we can use [aeiou] for match.
    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program of regular expression 
        
    # declaring a function which checks for vowel in a string 
    def contains_vowel(str) 
      str =~ /[aeiou]/ 
    end
        
    # Driver code 
        
    # Geeks has vowel at index 1, so function returns 1 
    puts( contains_vowel("Geeks") ) 
        
    # bcd has no vowel, so return nil and nothing is printed 
    puts( contains_vowel("bcd") ) 

    chevron_right

    
    

    Output :



    1

    There are different short expressions for specifying character ranges :

    • \w is equivalent to [0-9a-zA-Z_]
    • \d is the same as [0-9]
    • \s matches white space
    • \W anything that’s not in [0-9a-zA-Z_]
    • \D anything that’s not a number
    • \S anything that’s not a space
    • The dot character . matches all but does not match new line. If you want to search . character, then you have to escape it.>/li>

    To know more about Regular Expression please refer to Regular Expressions in Ruby.

    Ruby Collection

    Arrays

    An array is a collection of different or similar items, stored at contiguous memory locations. The idea is to store multiple items of the same type together which can be referred to by a common name. In general, an array is created by listing the elements which will be separated by commas and enclosed between the square brackets[].
    Syntax :

    name_of_array= Array.new
    ["Geeks", 55, 61, "GFG"]

    Retrieving Or Accessing Elements from Array
    In Ruby, there are several ways to retrieve the elements from the array. Ruby arrays provide a lot of different methods to access the array element. But the most used way is to use the index of an array.
    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the  
    # accessing the elements of the array 
        
    # creating string using [] 
    str = ["GFG", "G4G", "Sudo", "Geeks"
        
    # accessing array elements 
    # using index 
    puts str[1
        
    # using the negative index 
    puts str[-1

    chevron_right

    
    

    Output :

    G4G
    Geeks
    

    To know more about Array please refer to Ruby Array

    Hashes

    Hash is a data structure that maintains a set of objects which are termed as the keys and each key associates a value with it. In simple words, a hash is a collection of unique keys and their values. A hash is created using the hash literal which is a comma-separated list of key/value pairs and it always enclosed within curly braces {}. There are different ways to create a hash :
    Syntax :

    hash_variable = Hash.new

    Fetching hash values: To fetch a hash value always put the required key within the square bracket [].
    Example :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the creation 
    # of hashes and fetching the hash values 
        
    #!/usr/bin/ruby 
        
    # Creating a hash using new class method 
    # without the default value 
    geeks = Hash.new
        
    # empty hash will return nothing on display 
    puts "#{geeks[4]}"
        
    # creating hash using new class method 
    # providing default value 
    # this could be written as  
    # geeks = Hash.new "GFG" 
    geeks_default = Hash.new("GFG"
        
    # it will return GFG for every index of hash 
    puts "#{geeks_default[0]}"
    puts "#{geeks_default[7]}"
        
    # creating hash using {} braces 
    geeks_hash1 = {"DS" => 1, "Java" => 2
        
        
    # fetching values of hash using [] 
    puts geeks_hash1['DS']    
    puts geeks_hash1['Java']   

    chevron_right

    
    

    Output :

    GFG
    GFG
    1
    2

    To know more about Hashes please refer to Ruby Hashes

    Strings

    In Ruby, string is a sequence of one or more characters. It may consist of numbers, letters, or symbols. Here strings are the objects, and apart from other languages, strings are mutable, i.e. strings can be changed in place instead of creating new strings.
    Creating and Accessing String Elements: User can access the string elements by using the square brackets []. In square brackets [], the user can pass the strings, ranges or indexes.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate the 
    # accessing of string 
        
    #!/usr/bin/ruby 
        
    # storing string in variable 
    str = "GeeksforGeeks Sudo Placements"
        
    # accessing the specified substring 
    puts str["Geeks"
    puts str['for'
        
    # passing index as an argument which returns  
    # the  specified character  
    puts str[3
        
    # passing the negative index as an argument which  
    # returns the specified character from the 
    # last of the string  
    puts str[-3
        
    # passing Two arguments which are separated  
    # by a comma that returns characters starting 
    # from the 1st index and the 2nd index is the 
    # number of characters 
    puts str[14, 10
        
    # using range operators in passed arguments 
    puts str[14 .. 17

    chevron_right

    
    

    Output :

    Geeks
    for
    k
    n
    Sudo Place
    Sudo

    To know more about Strings please refer to Ruby Strings




    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



    Improved By : Akanksha_Rai

    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.