Author: Saim Khalid

  • Ruby Arrays

    Ruby arrays are ordered collections of objects. They can hold objects like integer, number, hash, string, symbol or any other array.

    Its indexing starts with 0. The negative index starts with -1 from the end of the array. For example, -1 indicates last element of the array and 0 indicates first element of the array.


    Creating Ruby Arrays

    A Ruby array is created in many ways.

    • Using literal constructor []
    • Using new class method

    Using literal construct []

    A Ruby array is constructed using literal constructor []. A single array can contain different type of objects.

    For example, following array contains an integer, floating number and a string.

    exm = [4, 4.0, "Jose", ]   
    
    puts exm

    Output:

    Ruby Arrays 1

    Using new class method

    A Ruby array is constructed by calling ::new method with zero, one or more than one arguments.

    Syntax:

    1. arrayName = Array.new  

    To set the size of an array,

    Syntax:

    1. arrayName = Array.new(10)  

    Here, we have mentioned that array size is of 10 elements.

    To know the size of an array, either size or length method is used.

    Example:

    #!/usr/bin/ruby   
    
      
    
    exm = Array.new(10)   
    
    puts exm.size    
    
    puts exm.length

    Output:

    Ruby Arrays 2

    Example:

    #!/usr/bin/ruby   
    
    exm = Array("a"..."z")   
    
    puts "#{exm}"

    Output:

    Ruby Arrays 3

    Accessing Array Elements

    Ruby array elements can be accessed using #[] method. You can pass one or more than one arguments or even a range of arguments.

    #[] method  

    Example:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days[0]      
    
    puts days[10]   
    
    puts days[-2]     
    
    puts days[2, 3]   
    
    puts days[1..7]

    Output:

    Ruby Arrays 4

    at method

    To access a particular element, at method can also be used.

    Example:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days.at(0)   
    
    puts days.at(-1)   
    
    puts days.at(5)

    Output:

    Ruby Arrays 5

    slice method

    The slice method works similar to #[] method.

    fetch method

    The fetch method is used to provide a default value error for out of array range indices.

    Example:

    
    
    1. days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    2. puts days.fetch(10) 

    Output:

    Ruby Arrays 6

    Example:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days.fetch(10, "oops")

    Output:

    Ruby Arrays 7

    first and last method

    The first and last method will return first and last element of an array respectively.

    Example:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days.first   
    
    puts days.last

    Output:

    Ruby Arrays 8

    take method

    The take method returns the first n elements of an array.

    Example:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days.take(1)   
    
    puts days.take(2)

    Output:

    Ruby Arrays 9

    drop method

    The drop method is the opposite of take method. It returns elements after n elements have been dropped.

    Example:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days.drop(5)   
    
    puts days.drop(6)days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days.drop(5)   
    
    puts days.drop(6)

    Output:

    Ruby Arrays 10

    Adding Items to Array

    Ruby array elements can be added in different ways.

    • push or <<
    • unshift
    • insert

    push or <<

    Using push or <<, items can be added at the end of an array.

    Example:

    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]   
    
    puts days.push("Today")   
    
    puts days << ("Tomorrow")

    Output:

    Ruby Arrays 11

    unshift

    Using unshift, a new element can be added at the beginning of an array.

    Example:

    days = ["Fri", "Sat", "Sun"]   
    
    puts days.unshift("Today")

    Output:

    Ruby Arrays 12

    insert

    Using insert, a new element can be added at any position in an array. Here, first we need to mention the index number at which we want to position the element.

    Example:

    days = ["Fri", "Sat", "Sun"]   
    
    puts days.insert(2, "Thursday")

    Output:

    Ruby Arrays 13

    Removing Items from Array

    Ruby array elements can be removed in different ways.

    • pop
    • shift
    • delete
    • uniq

    pop

    Using pop, items can be removed from the end of an array. It returns the removed item.

    Example:

    days = ["Fri", "Sat", "Sun"]   
    
    puts days.pop

    Output:

    Ruby Arrays 14

    shift

    Using shift, items can be removed from the start of an array. It returns the removed item.

    Example:

    
    
    1. days = ["Fri", "Sat", "Sun"]   
    2. puts days.shift 

    Output:

    Ruby Arrays 15

    delete

    Using delete, items can be removed from anywhere in an array. It returns the removed item.

    Example:

    days = ["Fri", "Sat", "Sun"]   
    
    puts days.delete("Sat")

    Output:

    Ruby Arrays 16

    uniq

    Using uniq, duplicate elements can be removed from an array. It returns the remaining array.

    Example:

    days = ["Fri", "Sat", "Sun", "Sat"]   
    
    puts days.uniq
  • Ruby Strings

    Ruby string object holds and manipulates an arbitary sequence of bytes, typically representing characters. They are created using String::new or as literals.


    Quotes

    Ruby string literals are enclosed within single and double quotes.

    Example:

    #!/usr/bin/ruby   
    
      
    
    puts 'Hello everyone'   
    
    puts "Hello everyone"

    Output:

    Ruby string 1

    Accessing string elements

    You can access Ruby string elements in different parts with the help of square brackets []. Within square brackets write the index or string.

    Example:

    #!/usr/bin/ruby   
    
      
    
    msg = "This tutorial is from JavaTpoint."   
    
      
    
    puts msg["JavaTpoint"]   
    
    puts msg["tutorial"]   
    
      
    
    puts msg[0]   
    
      
    
    puts msg[0, 2]   
    
    puts msg[0..19]   
    
    puts msg[0, msg.length]   
    
    puts msg[-3]

    Output:

    Ruby string 2

    Multiline string

    Writing multiline string is very simple in Ruby language. We will show three ways to print multi line string.

    • String can be written within double quotes.
    • The % character is used and string is enclosed within / character.
    • In heredoc syntax, we use << and string is enclosed within word STRING.

    Example:

      
      
      1. puts "   
      2. A   
      3. AB   
      4. ABC   
      5. ABCD"   
      6.   
      7. puts %/   
      8. A   
      9. AB   
      10. ABC   
      11. ABCD/   
      12.   
      13. puts <<STRING   
      14. A   
      15. AB   
      16. ABC   
      17. ABCD   
      18. STRING 

      Output:

      Ruby string 3

      Variable Interpolation

      Ruby variable interpolation is replacing variables with values inside string literals. The variable name is put between #{ and } characters inside string literal.

      Example:

      #!/usr/bin/ruby   
      
        
      
      country = "India"   
      
      capital = "New Delhi"   
      
        
      
      puts "#{capital} is the capital of #{country}."

      Output:

      Ruby string 4

      Concatenating Strings

      Ruby concatenating string implies creating one string from multiple strings. You can join more than one string to form a single string by concatenating them.

      There are four ways to concatenate Ruby strings into single string:

      • Using plus sign in between strings.
      • Using a single space in between strings.
      • Using << sign in between strings.
      • Using concat method in between strings.

      Example:

      #!/usr/bin/ruby   
      
        
      
      string = "This is Ruby Tutorial" + " from JavaTpoint." + " Wish you all good luck."   
      
      puts string   
      
        
      
      string = "This is Ruby Tutorial" " from JavaTpoint." " Wish you all good luck."   
      
      puts string   
      
        
      
      string = "This is Ruby Tutorial" << " from JavaTpoint." << " Wish you all good luck."   
      
      puts string   
      
        
      
      string = "This is Ruby Tutorial".concat(" from JavaTpoint.").concat(" Wish you all good luck.")   
      
      puts string

      Output:

      Ruby string 5

      Freezing Strings

      In most programming languages strings are immutable. It means that an existing string can’t be modified, only a new string can be created out of them.

      In Ruby, by default strings are not immutable. To make them immutable, freeze method can be used.

      Example:

      #!/usr/bin/ruby   
      
        
      
      str = "Original string"   
      
      str << " is modified "   
      
      str << "is again modified"   
      
        
      
      puts str   
      
        
      
      str.freeze   
      
        
      
      #str << "And here modification will be failed after using freeze method"

      Output:

      Ruby string 6

      In the above output, we have made the string immutable by using freeze method. Last line is commented as no string can’t be modified any further.

      By uncommenting the last line, we’ll get an error as shown in the below output.

      Output:

      Ruby string 7

      Comparing Strings

      Ruby strings can be compared with three operators:

      • With == operator : Returns true or false
      • With eql? Operator : Returns true or false
      • With casecmp method : Returns 0 if matched or 1 if not matched

      Example:

      
      
      1. #!/usr/bin/ruby   
      2.   
      3. puts "abc" == "abc"   
      4. puts "as ab" == "ab ab"   
      5. puts "23" == "32"   
      6.   
      7. puts "ttt".eql? "ttt"   
      8. puts "12".eql? "12"   
      9.   
      10. puts "Java".casecmp "Java"   
      11. puts "Java".casecmp "java"   
      12. puts "Java".casecmp "ja"  

      Output:

      Ruby string 8

    1. Ruby Modules

      Ruby module is a collection of methods and constants. A module method may be instance method or module method.

      Instance methods are methods in a class when module is included.

      Module methods may be called without creating an encapsulating object while instance methods may not.

      They are similar to classes as they hold a collection of methods, class definitions, constants and other modules. They are defined like classes. Objects or subclasses can not be created using modules. There is no module hierarchy of inheritance.

      Modules basically serve two purposes:

      • They act as namespace. They prevent the name clashes.
      • They allow the mixin facility to share functionality between classes.

      Syntax:

      module ModuleName  
      
         statement1  
      
         statement2  
      
         ...........  
      
      end

      Module name should start with a capital letter.


      Module Namespaces

      While writing larger files, a lot of reusable codes are generated. These codes are organized into classes, which can be inserted into a file.

      For example, if two persons have the same method name in different files. And both the files need to be included in a third file. Then it may create a problem as the method name in both included files is same.

      Here, module mechanism comes into play. Modules define a namespace in which you can define your methods and constants without over riding by other methods and constants.

      Example:

      Suppose, in file1.rb, we have defined number of different type of library books like fiction, horror, etc.

      In file2.rb, we have defined the number of novels read and left to read including fiction novels.

      In file3.rb, we need to load both the files file1 and file2. Here we will use module mechanism.

      file1.rb

      #!/usr/bin/ruby   
      
        
      
      # Module defined in file1.rb file   
      
        
      
      module Library   
      
         num_of_books = 300   
      
         def Library.fiction(120)   
      
         # ..   
      
         end   
      
         def Library.horror(180)   
      
         # ..   
      
         end   
      
      end

      file2.rb

      #!/usr/bin/ruby   
      
        
      
      # Module defined in file2.rb file   
      
        
      
      module Novel   
      
         total = 123   
      
         read = 25   
      
         def Novel.fiction(left)   
      
         # ...   
      
         end   
      
      end

      file3.rb

      require "Library"   
      
      require "Novel"   
      
        
      
      x = Library.fiction(Library::num_of_books)   
      
      y = Novel.fiction(Novel::total)

      A module method is called by preceding its name with the module’s name and a period, and you reference a constant using the module name and two colons.


      Module Mixins

      Ruby doesn’t support multiple inheritance. Modules eliminate the need of multiple inheritance using mixin in Ruby.

      A module doesn’t have instances because it is not a class. However, a module can be included within a class.

      When you include a module within a class, the class will have access to the methods of the module.

      Example:

      
      
    2. module Name   
    3.    def bella   
    4.    end   
    5.    def ana   
    6.    end   
    7. end   
    8. module Job   
    9.    def editor   
    10.    end   
    11.    def writer   
    12.    end   
    13. end   
    14.   
    15. class Combo   
    16. include Name   
    17. include Job   
    18.    def f   
    19.    end   
    20. end   
    21.   
    22. final=Combo.new   
    23. final.bella   
    24. final.ana   
    25. final.editor   
    26. final.writer   
    27. final.f  
    28. Here, module Name consists of methods bella and ana. Module Job consists of methods editor and writer. The class Combo includes both the modules due to which class Combo can access all the four methods. Hence, class Combo works as mixin.

      The methods of a module that are mixed into a class can either be an instance method or a class method. It depends upon how you add mixin to the class.

    29. Ruby Blocks

      Ruby code blocks are called closures in other programming languages. It consist of a group of codes which is always enclosed with braces or written between do..end. The braces syntax always have the higher precedence over the do..end syntax. Braces have high precedence and do has low precedence.

      A block is written in two ways,

      • Multi-line between do and end (multi-line blocks are niot inline)
      • Inline between braces {}

      Both are same and have the same functionality.

      To invoke a block, you need to have a function with the same name as the block.

      A block is always invoked with a function. Blocks can have their own arguments.

      syntax:

      block_name{  
      
         statement1  
      
         statement2  
      
         ..........  
      
      }

      Example:

      The below example shows the multi-line block.

      
      
      1. [10, 20, 30].each do |n|   
      2.  puts n   
      3. end

      Output:

      Ruby Blocks 1

      Below example shows the inline block.

      [10, 20, 30].each {|n| puts n}  

      Output:

      Ruby Blocks 2

      The yield statement

      The yield statement is used to call a block within a method with a value.

      Example:

      #!/usr/bin/ruby   
      
        
      
      def met   
      
         puts "This is method"   
      
         yield   
      
         puts "You will be back to method"   
      
         yield   
      
      end   
      
      met {puts "This is block"}

      Output:

      Ruby Blocks 3

      While the execution of met method, when we reach at yield line, the code inside the block is executed. When block execution finishes, code for met method continues.

      Passing parameters with yield statement

      One or more than one parameter can be passed with the yield statement.

      Example:

      
      
      1. #!/usr/bin/ruby   
      2.   
      3. def met   
      4.    yield 1   
      5.    puts "This is method"   
      6.    yield 2   
      7. end   
      8. met {|i| puts "This is block #{i}"}   

      Output:

      Ruby Blocks 4

      Block Variables

      We can use same variable outside and inside a block parameter. Let’s see the following example.

      Example:

      
      
      1. #!/usr/bin/ruby   
      2.   
      3.     x = "Outer variable"    
      4.     3.times do |x|    
      5.       puts "Inside the block: #{x}"    
      6.     end    
      7.     puts "Outside the block: #{x}"  

      Output:

      Ruby Blocks 5

      In this example, we are using same variable inside the block as the block parameter x and outside the block as a variable x.


      BEGIN and END block

      Ruby BEGIN and END block is used to declare that file is being loaded and file has been loaded respectively.

      Example:

      
      
      1. #!/usr/bin/ruby   
      2.   
      3. BEGIN {   
      4.   puts "code block is being loaded"   
      5. }   
      6.   
      7. END {   
      8.   puts "code block has been loaded"   
      9. }   
      10. puts "This is the code block"

      Output:

      Ruby Blocks 6

      Ampersand parameter (&block)

      The &block is a way to pass a reference (instead of a local variable) to the block to a method.

      Here, block word after the & is just a name for the reference, any other name can be used instead of this.

      Example:

      
      
      1. def met(&block)   
      2.   puts "This is method"   
      3.   block.call   
      4. end   
      5. met { puts "This is &block example" }   

      Output:

      Ruby Blocks 7

      Here, the block variable inside method met is a reference to the block. It is executed with the call mehtod. The call method is same as yield method.


      Initializing objects with default values

      Ruby has an initializer called yield(self). Here, self is the object being initialized.

      Example:

      class Novel   
      
        attr_accessor :pages, :category   
      
        
      
        def initialize   
      
          yield(self)   
      
        end   
      
      end   
      
        
      
      novel = Novel.new do |n|   
      
        n.pages = 564   
      
        n.category = "thriller"   
      
      end   
      
        
      
      puts "I am reading a #{novel.category} novel which has #{novel.pages} pages."
    30. Ruby Methods

      Ruby methods prevent us from writing the same code in a program again and again. It is a set of expression that returns a value.

      Ruby methods are similar to the functions in other lnguages. They unite one or more repeatable statements into one single bundle.


      Defining Method

      To use a method, we need to first define it. Ruby method is defined with the def keyword followed by method name. At the end we need to use end keyword to denote that method has been defined.

      Methods name should always start with a lowercase letter. Otherwise, it may be misunderstood as a constant.

      Syntax:

      def methodName  
      
          code...  
      
      end

      Example:

      Ruby method 1

      Here, we have defined a method welcome using def keyword. The last line end keyword says that we are done with the method defining.

      Now let’s call this method. A method is called by just writing its name.

      Ruby method 2

      Defining Method with Parameter

      To call a particular person, we can define a method with parameter.

      Ruby method 3

      Here, #{name} is a way in Ruby to insert something into string. The bit inside the braces is turned into a string.

      Let’s call the method by passing a parameter Edward.

      Ruby method 4
    31. Ruby Class and Object

      Here, we will learn about Ruby objects and classes. In object-oriented programming language, we design programs using objects and classes.

      Object is a physical as well as logical entity whereas class is a logical entity only.


      Ruby Object

      Object is the default root of all Ruby objects. Ruby objects inherit from BasicObject (it is the parent class of all classes in Ruby) which allows creating alternate object hierarchies.

      Object mixes in the Kernel module which makes the built-in Kernel functions globally accessible.


      Creating object

      Objects in Ruby are created by calling new method of the class. It is a unique type of method and predefined in the Ruby library.

      Ruby objects are instances of the class.

      Syntax:

      objectName = className.new  

      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 Class and object 1

      Ruby Class

      Each Ruby class is an instance of class Class. Classes in Ruby are first-class objects.

      Ruby class always starts with the keyword class followed by the class name. Conventionally, for class name we use CamelCase. The class name should always start with a capital letter. Defining class is finished with end keyword.

      Syntax:

      class ClassName  
      
          codes...  
      
      end

      Example:

      Ruby Class and object 2

      In the above example, we have created a class Home using class keyword. The @love is an instance variable, and is available to all methods of class Home.

    32. Ruby Comments

      Ruby comments are non executable lines in a program. These lines are ignored by the interpreter hence they don’t execute while execution of a program. They are written by a programmer to explain their code so that others who look at the code will understand it in a better way.

      Types of Ruby comments:

      • Single line comment
      • multi line comment

      Ruby Single Line Comment

      The Ruby single line comment is used to comment only one line at a time. They are defined with # character.

      Syntax:

      1. #This is single line comment.  

      Example:

      i = 10  #Here i is a variable.   
      
      puts i

      Output:

      Ruby Comments 1

      The Ruby multi line comment is used to comment multiple lines at a time. They are defined with =begin at the starting and =end at the end of the line.

      Syntax:

      =begin  
      
          This  
      
          is  
      
          multi line  
      
          comment  
      
      =end

      Example:

      =begin   
      
      we are declaring   
      
      a variable i   
      
      in this program   
      
      =end   
      
      i = 10   
      
      puts i

      Output:

      Ruby Comments 2
    33. Ruby redo Statement

      Ruby redo statement is used to repeat the current iteration of the loop. The redo statement is executed without evaluating the loop’s condition.

      The redo statement is used inside a loop.

      Syntax:

      1. redo  

      Example:

      i = 0   
      
      while(i < 5)   # Prints "012345" instead of "01234"   
      
        puts i   
      
        i += 1   
      
         redo if i == 5   
      
      end

      Output:

      Ruby redo statement 1

      Ruby retry Statement

      Ruby retry statement is used to repeat the whole loop iteration from the start.

      The retry statement is used inside a loop.

      Syntax:

      1. retry  
    34. Ruby Break Statement

      The Ruby break statement is used to terminate a loop. It is mostly used in while loop where value is printed till the condition is true, then break statement terminates the loop.

      The break statement is called from inside the loop.

      Syntax:

      1. break  

      Example:

      i = 1   
      
      while true   
      
          if i*5 >= 25   
      
              break   
      
          end   
      
          puts i*5   
      
          i += 1   
      
      end

      Output:

      Ruby Break 1

      Ruby Next Statement

      The Ruby next statement is used to skip loop’s next iteration. Once the next statement is executed, no further iteration will be performed.

      The next statement in Ruby is equivalent to continue statement in other languages.

      Syntax:

      1. next  

      Example:

      for i in 5...11   
      
         if i == 7 then   
      
            next   
      
         end   
      
         puts i   
      
      end

      Output:

      Ruby Break 2
    35. Ruby Until Loop

      The Ruby until loop runs until the given condition evaluates to true. It exits the loop when condition becomes true. It is just opposite of the while loop which runs until the given condition evaluates to false.

      The until loop allows you to write code which is more readable and logical.

      Syntax:

      until conditional  
      
         code  
      
      end

      Example:

      i = 1   
      
      until i == 10   
      
          print i*10, "\n"   
      
          i += 1   
      
      end

      Output:

      Ruby until loop 1