Author: Saim Khalid

  • Ruby Socket Programming

    Sockets are the end points of a network communication channel, where client and server communicate to each other. They can communicate either on same machine or on different machines.

    Types of socket:

    • TCP Socket
    • UDP Socket
    • UNIX Socket

    There are two levels of socket, high and low. Low level access allows you to work on sockets that are supported by your system. It allows the implementation of both connectionless and connection oriented protocols. High level access allows you to work on network protocols like HTTP and FTP.

    Example1

    server1.rb

    #!/usr/bin/ruby   
    
    require 'socket'   
    
      
    
    server = TCPServer.open(2017)   
    
    loop {   
    
        client = server.accept   
    
        client.puts "Hello. This is socket programming"   
    
        client.close   
    
    }

    In the above code, the pre installed socket module need to be included. We are using 2017 port on our system. You can use any port.

    Start a loop, accept all connections made to port 2017 and send data to the client over socket networking.

    Lastly, close the socket.

    client1.rb

    #!/usr/bin/ruby   
    
    require 'socket'   
    
      
    
    hostname = 'localhost'   
    
    port = 2017   
    
      
    
    s = TCPSocket.open(hostname, port)   
    
      
    
    while line = s.gets   
    
        puts line.chomp   
    
    end   
    
    s.close

    In the above code, the pre installed socket module need to be included. Create a socket and connect it to port 2017.

    create a while loop to fetch all information sent over the socket.

    Lastly, close the socket.

    Output:

    Go to the terminal, change to the directory to which you have saved the above two files. We have saved it in our Desktop directory.

    Now to execute these files, we need to have the required permission. Run the following command in the terminal,

    chmod a+x *.rb  

    This command will make all the Ruby files executable present in this directory.

    Ruby Socket programming 1

    Now open two terminals. In the first terminal execute server script and in the second terminal execute client script with the following command.

    ruby filename.rb  
    Ruby Socket programming 2

    Multiple clients socket programming

    For multiple clients overs a socket programming, a loop and some threads will be needed to accept and respond to multiple clients.

    Example2

    server3.rb

    #!/usr/bin/env ruby -w   
    
    require "socket"   
    
    class Server   
    
      def initialize( port, ip )   
    
        @server = TCPServer.open( ip, port )   
    
        @connections = Hash.new   
    
        @rooms = Hash.new   
    
        @clients = Hash.new   
    
        @connections[:server] = @server   
    
        @connections[:rooms] = @rooms   
    
        @connections[:clients] = @clients   
    
        run   
    
      end   
    
      
    
      def run   
    
        loop {   
    
          Thread.start(@server.accept) do | client |   
    
            nick_name = client.gets.chomp.to_sym   
    
            @connections[:clients].each do |other_name, other_client|   
    
              if nick_name == other_name || client == other_client   
    
                client.puts "This username already exist"   
    
                Thread.kill self   
    
              end   
    
            end   
    
            puts "#{nick_name} #{client}"   
    
            @connections[:clients][nick_name] = client   
    
            client.puts "Connection established..."   
    
            listen_user_messages( nick_name, client )   
    
          end   
    
        }.join   
    
      end   
    
      
    
      def listen_user_messages( username, client )   
    
        loop {   
    
          msg = client.gets.chomp   
    
          @connections[:clients].each do |other_name, other_client|   
    
            unless other_name == username   
    
              other_client.puts "#{username.to_s}: #{msg}"   
    
            end   
    
          end   
    
        }   
    
      end   
    
    end   
    
      
    
    Server.new( 2019, "localhost" )

    In the above code, server will have the same port as client side to establish connection. Here we need one thread per connected user to handle all the possible users.

    The run method verify whether an entered name is unique or not. If username already exists, connection will be killed otherwise connection will be established.

    The listen_user_messages method listen to the user messages and send them to all the users.

    client3.rb

    #!/usr/bin/env ruby -w   
    
    require "socket"   
    
    class Client   
    
      def initialize( server )   
    
        @server = server   
    
        @request = nil   
    
        @response = nil   
    
        listen   
    
        send   
    
        @request.join   
    
        @response.join   
    
      end   
    
      
    
      def listen   
    
        @response = Thread.new do   
    
          loop {   
    
            msg = @server.gets.chomp   
    
            puts "#{msg}"   
    
          }   
    
        end   
    
      end   
    
      
    
      def send   
    
        puts "Enter your name:"   
    
        @request = Thread.new do   
    
          loop {   
    
            msg = $stdin.gets.chomp   
    
            @server.puts( msg )   
    
          }   
    
        end   
    
      end   
    
    end   
    
      
    
    server = TCPSocket.open( "localhost", 2019 )   
    
    Client.new( server )

    In the above code, class Client is created to handle users.

    Two threads are created in send and listen methods so that we can read/write messages at the same time.

    Output:

    Below snapshot shows chatting between two clients.

    Ruby Socket programming 3

    Output on server terminal is shown below.

    Ruby Socket programming 4
  • Ruby Regular Expression

    A regular expression is also spelled as regexp which holds a regular expression, used to match a pattern against strings. In Ruby, a pattern is written between forward slash characters. They describe the content of a string. Ruby regular expression is more similar to Perl regular expression.

    Syntax:

    /search string/  

    Ruby 1.9 uses Oniguruma regular expressions library but Ruby 2.0 uses Onigmo regular expressions library. Onigmo is a fork library of Oniguruma adding some new features.


    =∽ and #match operators

    The pattern matching is achieved by using =∽ and #match operators.

    =∽

    This is the basic matching pattern. Here two operands are used. One is a regular expression and other is a string. The regular expression is matched with the string.

    If a match is found, the operator returns index of first match otherwise nil.

    Example:

    Ruby Regular expression 1

    #match

    This operator returns a MatchData object on matching otherwise nil.

    Ruby Regular expression 2

    Metacharacters and Escapes

    Metacharacters have specific meaning in a pattern. To match a string, they are back slashed (\\\) or escaped. Some meta characters are (,), (.), (?), (+), (-), (*), [,], {,}.

    It returns the specific string when matched otherwise nil.

    Example:

    Ruby Regular expression 3

    Characters Classes

    Metacharacters have specific meaning in a pattern. To match a string, they are back slashed (\\\) or escaped.

    A character class is encircled within square brackets.

    [ab]

    Here, [ab] means a or b. It is the oppoite of /ab/ which means a and b.

    Example:

    Ruby Regular expression 4

    [a-d]

    Here, [a-d] is equivalent to [abcd]. The hyphen (-) character class represents range of characters.

    Example:

    Ruby Regular expression 5

    [^a-d]

    The ^ sign represents any other character which is not present in the range.

    Example:

    Ruby Regular expression 6

    Repetition

    Characters defined till now match a single character. With the help of repetition metacharacter, we can specify how many times they need to occur. These meta characters are called quantifiers.

    • *: Zero or more times
    • +: One or more times
    • ?: Zero or one times (optional)
    • {n}: Exactly n times
    • {n, }: n or more times
    • {,m}: m or less times
    • {n,m}: At least n and at most m times

    Example:

    Ruby Regular expression 7

    Grouping

    Grouping uses parentheses to group the terms together. Grouping the terms together make them one.

    Example:

    Ruby Regular expression 8

    In this example, first pattern matches a vowel followed by two characters.

    In the second pattern, it matches a vowel followed by a word character, twice.

    (?:..)

    This expression provides grouping without capturing. It combines term without creating a backreference.

    Example:

    Ruby Regular expression 9
  • Ruby OOPs Concept

    Ruby is a true object oriented language which can be embedded into Hypertext Markup Language. Everything in Ruby is an object. All the numbers, strings or even class is an object. The whole Ruby language is basically built on the concepts of object and data.

    OOPs is a programming concept that uses objects and their interactions to design applications and computer programs.

    Following are some basic concepts in OOPs:EncapsulationPolymorphismInheritanceAbstraction

    Encapsulation: It hides the implementation details of a class from other objects due to which a class is unavailable to the rest of the code. Its main purpose is to protect data from data manipulation.

    Polymorphism: It is the ability to represent an operator or function in different ways for different data input.

    Inheritance: It creates new classes from pre defined classes. New class inherit behaviors of its parent class which is referred as superclass. In this way, pre defined classes can be made more reusable and useful.

    Abstraction: It hides the complexity of a class by modelling classes appropriate to the problem.


    Ruby Class

    Ruby class defines blueprint of a data type. It defines what does that class name means.

    A class is defined with a class keyword followed by the class name and is ended with end keyword.

    Conventionally, class name must begin with a capital letter. Class name with more than one word run together with each word capitalized and no separating characters.

    Creating Class

    Example:

    We will create a class Java with following command,

    class Greeter  Ruby Regular Expression
    

    Ruby Oops concept 1

    A new class Java is created. The @name is an instance variable available to all the methods of the Java class. It is used by say_welcome and say_bye.


    Ruby Objects

    In Ruby, everything is an object. When we create objects, they communicate together through methods. Hence, an object is a combination of data and methods.

    To create an object, first, we define a class. Single class can be used to create many objects. Objects are declared using new keyword.

    Creating Object

    Example:

    We have a class named Java. Now, let’s create an object java and use it with following command,

    java = Java.new("John")  

    Ruby Oops concept 2

    Once java object is created, it will use John as the name.


    Ruby Methods

    Methods are functions which are defined inside the body of a class. Data in Ruby is accessible only via methods. There is a follow path in which Ruby looks when a method is called. To find out the method lookup chain we can use ancestors method.

    Defining Method

    A method is defined with def keyword and ends with end keyword.

    We are defining a method name which will display the following message.Ruby Oops concept 3

    The def keyword starts the definition of method name. Then we write body of the mehtod. Last line end indicates that method is defined.

    Instance Methods

    The instance methods are also defined with def keyword and they can be used using a class instance only.

    Example:

    #!/usr/bin/ruby -w   
    
      
    
    # define a class   
    
    class Circle   
    
       # constructor method   
    
       def initialize(r)   
    
          @radius = r   
    
       end   
    
       # instance method   
    
       def getArea   
    
          3.14 * @radius * @radius   
    
       end   
    
    end   
    
      
    
    # create an object   
    
    circle = Circle.new(2)   
    
      
    
    # call instance methods   
    
    a = circle.getArea()   
    
    puts "Area of the box is : #{a}"

    Output:Ruby Oops concept 4


    Ruby Inheritance

    In inheritance, we create new classes using pre defined classes. Newly created classes are called derived classes and classes from which they are derived are called base classes. With inheritance, a code can be reused again which reduces the complexity of a program.

    Ruby does not support multiple levels of inheritance. Instead it supports mixins.

    In Ruby, < character is used to create a subclass. The syntax is shown below:

    parentClass < subClass  

    Example:

    #!/usr/bin/ruby   
    
      
    
    class Parent   
    
      
    
        def initialize   
    
            puts "Parent class created"   
    
        end   
    
    end   
    
      
    
    class Child < Parent   
    
      
    
       def initialize   
    
           super   
    
           puts "Child class created"   
    
       end   
    
    end   
    
      
    
    Parent.new   
    
    Child.new

    In the above example, two classes are created. One is base Parent class and other is derived Child class.

    The super method calls the constructor of the Parent class.

    From the last two line, we instantiate both the classes.

    Output:Ruby Oops concept 5

    In the output, first the Parent class is created, derived Child class also calls the constructor of its parent class and then Child class is created.


    Ruby Constructor

    A constructor is automatically called when an object is created. They do not return any values. In Ruby, they are called initialize.

    A constructor’s main purpose is to initiate the state of an object. They can’t be inherited. The parent object constructor is called with super method.

    Example:

    #!/usr/bin/ruby   
    
      
    
    class Parent   
    
      
    
        def initialize   
    
            puts "Parent is created"   
    
        end   
    
      
    
    end   
    
      
    
    Parent.new

    Output:Ruby Oops concept 6

  • Ruby Exceptions

    Ruby exception is an object, an instance of the class Exception or descendent of that class. It represents some exceptional condition.

    In a Ruby program, when something goes wrong, it throws an exceptional behavior. By default Ruby program terminates on throwing an exception.

    We can declare some exception handlers within Ruby. An exception handler is a block of code which is executed when exception occurs in some other block of code.

    Exceptions are handled in two ways. Either you can terminate the program or deal with the exception. To deal with an exception, you can provide a rescue clause. By providing this, program control flows to the rescue clause.

    When an exception is raised but not handled, global variable $! contains the current exception and $@ contains the current exception’s backtrace.

    Ruby predefined classes like Exception and its children helps you to handle errors of your program. In Ruby exception hierarchy, most of the sub classes extend class StandardError. These are the normal exceptions.


    Ruby Class Exceptions

    Built-in subclasses of exception are as follows:

    • NoMemoryError
    • ScriptError
    • SecurityError
    • SignalException
    • StandardError
    • SystenExit
    • SystemStackError
    • fatal – impossible to rescue

    Example:

    def raise_exception     
    
      puts 'I am before the raise.'     
    
      raise 'oops! An error has occured'     
    
      puts 'I am after the raise'     
    
    end     
    
    raise_exception

    Output:

    Ruby exceptions 1

    The raise method comes from the Kernel module.


    Handling an Exception

    To handle exception, the code that raises exception is enclosed within begin-end block. Using rescue clauses we can state type of exceptions we want to handle.

    Example:

    def raise_and_rescue     
    
      begin     
    
        puts 'Before the raise.'     
    
        raise 'An error occured.'     
    
        puts 'After the raise.'     
    
      rescue     
    
        puts 'Code rescued.'     
    
      end     
    
      puts 'After the begin block.'     
    
    end     
    
    raise_and_rescue

    Output:

    Ruby exceptions 2

    In the above example, interrupted code does not run completely. After exception handling code resumes after the begin-end block.

    If no argument is defined in the rescue clause, the parameter defaults to StandardError. Each rescue clause specify multiple exceptions to catch. If raise is used without any parameters, exception may re-raised.

    The rescue clauses are written in a begin/rescue block. Exceptions if not handled by one rescue clause will br handled with the next one.

    
    
    1.   begin  
    2. code..  
    3. rescue OneTypeOfException  
    4. code..  
    5. rescue AnotherTypeOfException  
    6.  code..  
    7. else  
    8.   # Other exceptions  
    9. end  

    In the begin block, each rescue clause with the raised exception will be compared against each of parameters in turn. It will be matched when the type of error thrown and exception named in the rescue clause is either same or is a superclass of that exception. The else clause is executed if body of begin statement is completed without exceptions. If an exception occurs, else clause will not be executed.


    Exception Object

    Exception objects are normal objects. A rescued exception can be hold to a variable within the rescue clause.

    Example:

    begin   
    
      raise 'an exception'   
    
    rescue ZeroDivisionError => e   
    
      puts "Exception Class: #{ e.class.name }"   
    
      puts "Exception Message: #{ e.message }"   
    
      puts "Exception Backtrace: #{ e.backtrace }"   
    
    end

    The Exception class defines two methods that return details about the exception. The message method returns a string that define the explanation of error. The backtrace method returns an array of string that represent the call stack at that point where exception was raised.


    Using retry Statement

    Usaually in a rescue clause, the exception is captured and code resumes after begin block. Using retry statement, the rescue block code can be resumed from begin after capturing an exception.

    Syntax:

    begin  
    
       code....  
    
    rescue  
    
        # capture exceptions  
    
        retry  # program will run from the begin block  
    
    end

    Example:

    #!/usr/bin/ruby   
    
      
    
    begin   
    
       x = Dir.mkdir "alreadyExist"   
    
       if x   
    
          puts "Directory created"   
    
       end   
    
    rescue   
    
       y = "newDir"   
    
       retry   
    
    end

    The above program runs as follows:

    Step 1 In the begin block, code is written to make a directory that already exists.

    Step 2 This will throw an error.

    Step 3 In rescue block, y was reassigned.

    Step 4 The retry statement will go to the begin block.

    Step 5 Directory will be created.


    Using raise Statement

    The raise statement is used to raise an exception.

    Syntax:

    raise   

    Or,

    raise ExceptionType, "Error Message"  

    Or,

    raise ExceptionType, "Error Message"  

    Or,

    raise ExceptionType, "Error Message" condition  

    The first one re-raises the current exception. It is used for exception handlers where exception is intercepted before passing it on.

    The second one creates a new RuntimeError exception. This exception is then raised up the call stack.

    The third one uses first argument to create an exception, then sets associated message to the second argument.

    The fourth one similar to third one. In this you can add any conditional statement to raise an exception.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2.   
    3. begin     
    4.     puts 'code before raise.'     
    5.     raise 'exception occurred.'     
    6.     puts 'code after raise.'     
    7. rescue     
    8.     puts 'I am rescued.'     
    9. end     
    10. puts 'code after begin block.'

    Output:

    Ruby exceptions 3

    Using ensure Statement

    There is an ensure clause which guarantees some processing at the end of code. The ensure block always run whether an exception is raised or not. It is placed after last rescue clause and will always executed as the block terminates.

    The ensure block will run at any case whether an exception arises, exception is rescued or code is terminated by uncaught exception.

    Syntax:

    begin   
    
      code..  
    
       #..raise exception  
    
    rescue   
    
       #.. exception is rescued  
    
    ensure   
    
       #.. This code will always execute.  
    
    end

    Example:

    begin   
    
      raise 'Exception'   
    
    rescue Exception => e   
    
      puts e.message   
    
      puts e.backtrace.inspect   
    
    ensure   
    
      puts "The ensure code will always run"   
    
    end

    Output:

    Ruby exceptions 4

    Using else Statement

    The else clause is always present after rescue clause and before ensure clause. If no exceptions are raised, then only else block is executed.

    Syntax:

    begin   
    
       code..   
    
       #..raise exception  
    
    rescue   
    
       # .. exception is rescued  
    
    else  
    
       #.. executes if there is no exception  
    
    ensure   
    
       #..  This code will always execute.  
    
    end

    Example:

    
    
    1. begin   
    2.  # raise 'A test exception.'   
    3.  puts "no exception is raised"   
    4. rescue Exception => e   
    5.   puts e.message   
    6.   puts e.backtrace.inspect   
    7. else   
    8.    puts "else code will be executed as no exception is raised."   
    9. ensure   
    10.   puts "ensure code will run"   
    11. end

    Output:

    Ruby exceptions 5

    Ruby Catch and Throw

    Ruby catch and throw provide a way to jump from the execution early when no further work is needed in a code.

    The catch defines a block that is labeled with a given name. It is used to jump out of nested code. Using catch, the block will be executed normally until throw is encountered.

    The catch and throw method is faster than rescue and raise clauses. Hence, it is more suitable to use.

    Syntax:

    throw :lablename  
    
    #.. this  code will not be executed  
    
    catch :lablename do  
    
    #.. matching catch will be executed after a throw is encountered.  
    
    end

    Or,

    throw :lablename condition  
    
    #.. this code will not be executed  
    
    catch :lablename do  
    
    #.. matching catch will be executed after a throw is encountered.  
    
    end

    Example:

    
    
    1. def promptAndGet(prompt)   
    2.    print prompt   
    3.    res = readline.chomp   
    4.    throw :quitRequested if res == "!"   
    5.    return res   
    6. end   
    7.   
    8. catch :quitRequested do   
    9.    name = promptAndGet("Name: ")   
    10.    age = promptAndGet("Occupation: ")   
    11.    # ..   
    12.    # process information   
    13. end   
    14. promptAndGet("Name:")

    Output:

    Ruby exceptions 6
  • Ruby Directories

    Class Dir has directory streams as objects which represents directories in underlying file system.

    Directories are handled with Dir class.


    Creating a Directory

    To create a directory mkdir command is used. You can give permission to a directory if you want.

    Syntax:

    Dir.mkdir "dirName" , permission  

    Example:

    Dir.mkdir "project"  

    We have created a directory “project” in out system.


    Checking a Directory exists or not

    To check whether a directory exists or not exists? Method is used.

    Syntax:

    puts Dir.exists? "dirName"  

    Example:

    #!/usr/bin/ruby   
    
      
    
    puts Dir.exists? "project"   
    
    puts Dir.exists? "pproject"

    Output:

    Ruby directories 1

    the correct directory name display true and wrong directory name display false.


    Current Working Directory

    To know the current working directory pwd method is used.

    Syntax:

    puts Dir.pwd  

    Example:

    puts Dir.pwd   

    Output:

    Ruby directories 2

    Removing Directory

    To remove a directory, rmdir, unlink or delete methods are used. They perform same function for a Ruby directory.

    Syntax:

    1. Dir.rmdir “dirName”  

    Example:

    #!/usr/bin/ruby   
    
      
    
    Dir.rmdir "project"   
    
    puts Dir.exists? "project"

    Output:

    Ruby directories 3

    The exists method returns false as this directory is no longer present.

  • Ruby File I/O

    Ruby I/O is a way to interact with your system. Data is sent in the form of bytes/characters. IO class is the basis for all input and output in Ruby. It may be duplexed, hence may use more than one native operating system stream.

    IO has a subclass as File class which allows reading and writing files in Ruby. The two classes are closely associated. IO object represent readable/writable interactions to keyboards and screens.


    Common modes in I/O port

    • “r”: read-only mode is the default mode starts at beginning of file.
    • “r+”: read-write mode, starts at beginning of file.
    • “w”: write-only mode, either creates a new file or truncates an existing file for writing.
    • “w+”: read-write mode, either creates a new file or truncates an existing file for reading and writing.
    • “a”: write-only mode, if file exists it will append the file othrwise a new file will be created for writing only.
    • “a+”: read and write mode, if file exists it will append the file othrwise a new file will be created for writing and reading.

    IO Console

    The IO console provides different methods to interact with console. The class IO provides following basic methods:

    • IO::console
    • IO#raw#raw!
    • IO#cooked
    • IO#cooked!
    • IO#getch
    • IO#echo=
    • IO#echo?
    • IO#noecho
    • IO#winsize
    • IO#winsize=
    • IO#iflush
    • IO#ioflush
    • IO#oflush

    Ruby opening a file

    A Ruby file can be created using different methods for reading, writing or both.

    There are two methods to open a file in Ruby:

    • File.new method : Using this method a new file can be created for reading, writing or both.
    • File.open method : Using this method a new file object is created. That file object is assigned to a file.

    Difference between both the methods is that File.open method can be associated with a block while File.new method can’t.

    Syntax:

    f = File.new("fileName.rb")  

    Or,

    File.open("fileName.rb", "mode") do |f|  

    Example to create a file

    Let’s create a file in Ruby using File.open method to read or write data from files.

    Step 1) In file hello.rb, write the code to create a new file as shown below.

    #!/usr/bin/ruby   
    
    File.open('about', 'w') do |f|   
    
        f.puts "This is JavaTpoint"   
    
        f.write "You are reading Ruby tutorial.\n"   
    
        f << "Please visit our website.\n"   
    
    end

    Step 2) Type the following two commands in the console to view the created file.

    ruby hello.rb  
    
    cat about
    Ruby file io 1

    The new file is created and content is displayed in the terminal as shown above.


    Ruby reading a file

    There are three different methods to read a file.

    To return a single line, following syntax is used.

    Syntax:

    f.gets  
    
     code...

    To return the whole file after the current position, following syntax is used.

    Syntax:

    1. f.read  
    2.  code…  

    To return file as an array of lines, following syntax is used.

    Syntax:

    f.readlines  
    
     [code...]

    Example to read a file

    Let’s create a file in Ruby using File.open method to read or write data from files.

    Step 1) In file hello.rb, write the code to read an already existing file as shown below.

    1. #!/usr/bin/ruby   
    2. while line = gets   
    3.     puts line   
    4. end   

    Step 2) Type the following command in the console to read the file.

    ruby hello.rb about  
    Ruby file io 2

    Content of about file is displayed in the console.

    The sysread Method

    The sysread method is also used to read the content of a file. With the help of this method you can open a file in any mode.

    Example:

    In file hello.rb, write the code to read an already existing file as shown below.

    
    
    1. #!/usr/bin/ruby   
    2.   
    3. aFile = File.new("about.txt", "r")   
    4. if aFile   
    5.    content = aFile.sysread(40)   
    6.    puts content   
    7. else   
    8.    puts "Unable to open file!"   
    9. end  

    Output:

    Ruby file io 3

    The argument 40 will print till 40 characters from the file.


    Ruby writing a file

    With the help of syswrite method, you can write content into a file. File needs to be opened in write mode for this method.

    The new content will over ride the old content in an already existing file.

    Example:

    #!/usr/bin/ruby   
    
      
    
    aFile = File.new("about.txt", "r+")   
    
    if aFile   
    
       aFile.syswrite("New content is written in this file.\n")   
    
    end

    Output:

    Ruby file io 4

    Ruby renaming and deleting a file

    Ruby files are renamed using rename method and deleted using delete mehtod.

    To rename a file, following syntax is used.

    Syntax:

    File.rename("olderName.txt", "newName.txt")  

    Example:

    #!/usr/bin/ruby   
    
      
    
    File.rename("about.txt", "new.txt")

    Output:

    Ruby file io 5

    In the above output, about.txt file no longer exist as its name has been changed to new.txt file.

    To delete a file, following syntax is used.

    Syntax:

    File.delete("filename.txt")  

    Example:

    
    
    1. #!/usr/bin/ruby   
    2.   
    3. File.delete("new.txt")

    Output:

    Ruby file io 6

    In the above output, new.txt file no longer exist as it has been deleted.

  • Ruby Iterators

    Iterator is a concept used in object-oriented language. Iteration means doing one thing many times like a loop.

    The loop method is the simplest iterator. They return all the elements from a collection, one after the other. Arrays and hashes come in the category of collection.


    Ruby Each Iterator

    The Ruby each iterator returns all the elements from a hash or array.

    Syntax:

    (collection).each do |variable|  
    
      code...  
    
    end

    Here collection can be any array, range or hash.

    Example:

    #!/usr/bin/ruby   
    
    (1...5).each do |i|   
    
       puts i   
    
    end

    Output:

    Ruby iterators 1

    Ruby Times Iterator

    A loop is executed specified number of times by the times iterator. Loop will start from zero till one less than specified number.

    Syntax:

    x.times do |variable|  
    
      code...  
    
    end

    Here, at place of x we need to define number to iterate the loop.

    Example:

    #!/usr/bin/ruby   
    
    5.times do |n|   
    
      puts n   
    
    end

    Output:

    Ruby iterators 2

    Ruby Upto and Downto Iterators

    An upto iterator iterates from number x to number y.

    Syntax:

    x.upto(y) do |variable|  
    
      code  
    
    end

    Example:

    #!/usr/bin/ruby   
    
    1.upto(5) do |n|   
    
      puts n   
    
    end

    Output:

    Ruby iterators 3

    Ruby Step Iterator

    A step iterator is used to iterate while skipping over a range.

    Syntax:

    (controller).step(x) do |variable|  
    
      code  
    
    end

    Here, x is the range which will be skipped during iteration.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2. (10..50).step(5) do |n|   
    3.   puts n   
    4. end

    Output:

    Ruby iterators 4

    Ruby Each_Line Iterator

    A each_line iterator is used to iterate over a new line in a string.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2. "All\nthe\nwords\nare\nprinted\nin\na\nnew\line.".each_line do |line|   
    3. puts line   
    4. end  

    Output:

    Ruby iterators 5
  • Ruby Ranges

    Ruby range represents a set of values with a beginning and an end. They can be constructed using s..e and s…e literals or with ::new.

    The ranges which has .. in them, run from beginning to end inclusively. The ranges which has … in them, run exclusively the end value.

    puts (-5..-1).to_a       
    
    puts (-5...-1).to_a       
    
    puts ('a'..'e').to_a      
    
    puts ('a'...'e').to_a

    Output:

    Ruby rangers 1

    Ruby has a variety of ways to define ranges.

    • Ranges as sequences
    • Ranges as conditions
    • Ranges as intervals

    Ranges as Sequences

    The most natural way to define a range is in sequence. They have a start point and an end point. They are created using either .. or … operators.

    We are taking a sample range from 0 to 5. The following operations are performed on this range.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2.   
    3. range = 0..5   
    4.   
    5. puts range.include?(3)   
    6. ans = range.min   
    7. puts "Minimum value is #{ans}"   
    8.   
    9. ans = range.max   
    10. puts "Maximum value is #{ans}"   
    11.   
    12. ans = range.reject {|i| i < 5 }   
    13. puts "Rejected values are #{ans}"   
    14.   
    15. range.each do |digit|   
    16.    puts "In Loop #{digit}"   
    17. end  

    Output:

    Ruby rangers 2

    Ranges as Conditions

    Ranges are also defined as conditional expressions. Different conditions are defined in a set of lines. These conditions are enclosed within start statement and end statement.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2. budget = 50000   
    3.   
    4. watch = case budget   
    5.    when 100..1000 then "Local"   
    6.    when 1000..10000 then "Titan"   
    7.    when 5000..30000 then "Fossil"   
    8.    when 30000..100000 then "Rolex"   
    9.    else "No stock"   
    10. end   
    11.   
    12. puts watch

    Output:

    Ruby rangers 3

    Ranges as Intervals

    Ranges can also be defined in terms of intervals. Intervals are represented by === case equality operator.

    Example:

    #!/usr/bin/ruby   
    
    if (('a'..'z') === 'v')   
    
      puts "v lies in the above range"   
    
    end   
    
      
    
    if (('50'..'90') === 99)   
    
      puts "z lies in the above range"   
    
    end

    Output:

    Ruby rangers 4

    Ruby Reverse Range

    Ruby reverse range operator does not return any value. If left side value is larger than right side value in a range, no vlaue will be returned.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2.     puts (5..1).to_a  

    Nothing will be returned in the output for the above example.

    To print a reverse order, you can use reverse method in a normal range as shown below.

    Example:

    #!/usr/bin/ruby   
    
        puts (1..5).to_a.reverse

    Output:

    Ruby rangers 5
  • Ruby Date & Time

    Ruby has Mainly three classes related to date and time in its documentation.

    • Date
    • DateTime
    • Time

    Date

    Ruby date provides two classes, Date and DateTime.

    To understand the concept of date, first we need to understand some terms.

    • Calendar date: The calendar date is a particular day within a calendar month within a year.
    • Ordinal date: The ordinal date is a particular day of a calendar year identified by its ordinal number.
    • Week date: The week date is a day identified by calendar week and day numbers. The first calendar week of the year is the one which includes first Thursday of that year.
    • Julian day number: The julian day number is in elapsed day since noon on January 1, 4713 BCE.
    • Modified julian day number: The modified julian day number is in elapsed day since midnight on November 17, 1858 CE.

    The Date object is created with ::new, ::parse, ::today, ::jd, ::strptime, etc. All date objects are immutable, hence they can’t modify themselves.

    Example:

    require 'date'   
    
      
    
    puts Date.new(2017,4,3)            
    
    puts Date.jd(2451877)               
    
    puts Date.ordinal(2017,3)         
    
    puts Date.commercial(2017,5,6)     
    
    puts Date.parse('2017-02-03')    
    
    puts Date.strptime('03-02-2017', '%d-%m-%Y')                           
    
    puts Time.new(2017,10,8).to_date

    Output:

    Ruby date time 1

    The Date object has various methods as shown in the below example.

    Example:

    require 'date'   
    
      
    
    d = Date.parse('4th Mar 2017')   
    
                                   
    
    puts d.year                        
    
    puts d.mon                         
    
    puts d.mday                        
    
    puts  d.wday                        
    
    puts d += 1                        
    
    puts d.strftime('%a %d %b %Y')

    Output:

    Ruby date time 2

    DateTime

    Ruby DateTime is a subclass of Date. It easily handles date, hour, minute, second and offset.

    The DateTime object created with DateTime.new, DateTime.ordinal, DateTime.parse, DateTime.jd, DateTime.commercial, DateTime.now, etc.

    Example:

    require 'date'   
    
      
    
    puts DateTime.new(2017,3,4,5,6,7)

    Output:

    Ruby date time 3

    The last element of day, minute, second or hour can be fractional.

    The DateTime object has various methods as shown in the below example.

    Example:

    
    
    1. require 'date'   
    2.   
    3. d = DateTime.parse('4th Mar 2017 02:37:05+05:40')   
    4.                        
    5. puts d.hour                 
    6. puts d.min                 
    7. puts d.sec                  
    8. puts d.offset               
    9. puts d.zone                 
    10. puts d += Rational('1.0')   
    11.                        
    12. puts d = d.new_offset('+05:00')   
    13.                       
    14. puts d.strftime('%I:%M:%S %p')   
    15.                      
    16. puts d > DateTime.new(2000)   

    Output:

    Ruby date time 4

    Time

    Time class is an abstraction of dates and times. It is stored internally as the number of seconds since Epoch time. The Time class treats GMT (Grenwich Mean Time) and UTC (Coordinated Universal Time) equivalent.

    Times may appear equal but on comparison they may be different as all times may have fraction.

    Time implementation uses a signed 63 bit integer, Bignum or Rational. Time works slower when integer is used.


    AD

    Creating a new Time Instance

    A new Time instance can be created with ::new. This will use your current system’s time. Parts of time like year, month, day, hour, minute, etc can also be passed.

    While creating a new time instance, you need to pass at least a year. If only year is passed, then time will default to January 1 of that year at 00:00:00 with current system time zone.

    Example:

    puts Time.new          
    
    puts Time.new(2017, 3)       
    
    puts Time.new(2017, 3, 4)   
    
    puts Time.new(2017, 3, 4, 6, 5, 5, "+05:00")

    Output:

    Ruby date time 5

    Time with gm, utc and local functions

    Instead of using current system setting, you can also use GMT, local and UTC timezones.

    Example:

    
    
    1. puts Time.local(2017, 2, 5)    
    2.   
    3. puts Time.local(2017, 2, 5, 4, 30)     
    4.   
    5. puts Time.utc(2017, 2, 5, 4, 30)    
    6.   
    7. puts Time.gm(2017, 2, 5, 4, 30, 36)

    Output:

    Ruby date time 6

    Working with an instance of time

    After creating an instance of time, we can work on that time in following ways.

    Example:

    
    
    1. t = Time.new(1991, 07, 5, 9, 15, 33, "+09:00")   
    2. puts t.friday? #=> false   
    3. puts t.year #=> 1993   
    4. puts t.dst? #=> false   
    5. puts t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900   
    6. puts t.to_i #=> 730522800   
    7.   
    8. t1 = Time.new(2017)   
    9. t2 = Time.new(2015)   
    10.   
    11. puts t1 == t2 #=> false   
    12. puts t1 == t1 #=> true   
    13. puts t1 <  t2 #=> true   
    14. puts t1 >  t2 #=> false   
    15.   
    16. puts Time.new(2010,10,31).between?(t1, t2) #=> true 

    Output:

    Ruby date time 7

    Timezones and daylight savings time

    A Time object can be used to get all the information related to timezones. All the information will be displayed respective to current time of our system.

    Example:

    time = Time.new   
    
      
    
    puts time.zone         
    
    puts time.utc_offset   
    
    puts time.zone        
    
    puts time.isdst       
    
    puts time.utc?      
    
    puts time.localtime    
    
    puts time.gmtime      
    
    puts time.getlocal    
    
    puts time.getutc

    Output:

    Ruby date time 8
  • Ruby Hashes

    A Ruby hash is a collection of unique keys and their values. They are similar to arrays but array use integer as an index and hash use any object type. They are also called associative arrays, dictionaries or maps.

    If a hash is accessed with a key that does not exist, the method will return nil.

    Syntax:

    name = {"key1" => "value1", "key2" => "value2", "key3" => "value3"...}  
    
                        OR  
    
    name = {key1:  'value1', key2:  'value2', key3:  'value3'...}

    Creating Ruby Hash

    Ruby hash is created by writing key-value pair within {} curly braces.

    To fetch a hash value, write the required key within [] square bracket.

    Example:

    color = {   
    
        "Rose" => "red",   
    
        "Lily" => "purple",   
    
        "Marigold" => "yellow",   
    
        "Jasmine" => "white"   
    
      }   
    
      puts color['Rose']   
    
      puts color['Lily']   
    
      puts color['Marigold']   
    
      puts color['Jasmine']

    Output:

    Ruby hashes 1

    Modifying Ruby Hash

    A Ruby hash can be modified by adding or removing a key value pair in an already existing hash.

    Example:

    color = {   
    
        "Rose" => "red",   
    
        "Lily" => "purple",   
    
        "Marigold" => "yellow",   
    
        "Jasmine" => "white"   
    
      }   
    
      color['Tulip'] = "pink"   
    
      color.each do |key, value|   
    
      puts "#{key} color is #{value}"   
    
     end

    Output:

    Ruby hashes 2

    Ruby Hash Methods

    A Ruby hash has many methods. Some are public class methods and some public instance methods.

    Public Class Methods

    MethodDescription
    Hash[object]Create a new hash with given objects.
    new(obj)Return a new empty hash.
    try_convert(obj)Try to convert obj into hash.

    Public Instance Methods

    MethodDescription
    hsh==other_hashTwo hashes are equal if they contain same key and value pair.
    hsh[key]Retrieve value from the respective key.
    hsh[key] = valueAssociates new value to the given key.
    assoc(obj)Compare obj in the hash.
    clearRemove all key value pair from hash.
    compare_by_identityCompare hash keys by their identity.
    compare_by_identity?Return true if hash compare its keys by their identity.
    default(key=nil)Return default value.
    default = objSets the default value.
    delete(key)Delete key value pair.
    eachCall block once for each key in hash.
    empty?Return true if hash contains no key value pair.
    eql>(other)Return true if hash and other both have same content
    fetch(key[, default])Return value from hash for a given key.
    flattenReturn a new array that is a one-dimensional flattening of this hash.
    has_key?(key)Return true if given key is present in hash.
    has_value?(value)Return true if given value is present in hash for a key.
    include?(key)Return true if given key is present in hash.
    to_s/ inspectReturn content of hash as string.