Blog

  • 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.

  • 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
  • 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  
  • 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
  • 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
  • Ruby while Loop

    The Ruby while loop is used to iterate a program several times. If the number of iterations is not fixed for a program, while loop is used.

    Ruby while loop executes a condition while a condition is true. Once the condition becomes false, while loop stops its execution.

    Syntax:

    while conditional [do]  
    
       code  
    
    end
    Ruby while loop 1

    Example:

    #!/usr/bin/ruby   
    
    x = gets.chomp.to_i   
    
    while x >= 0    
    
      puts x   
    
      x -=1   
    
    end

    Output:

    Ruby while loop 2

    Ruby do while Loop

    The Ruby do while loop iterates a part of program several times. It is quite similar to a while loop with the only difference that loop will execute at least once. It is due to the fact that in do while loop, condition is written at the end of the code.

    Syntax:

    loop do   
    
      #code to be executed  
    
      break if booleanExpression  
    
    end

    Example:

    loop do   
    
      puts "Checking for answer"   
    
      answer = gets.chomp   
    
      if answer != '5'   
    
        break   
    
      end   
    
    end

    Output:

    Ruby while loop 3
  • Ruby for Loop

    Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if a program has fixed number of iterations.

    Ruby for loop will execute once for each element in expression.

    Syntax:

    for variable [, variable ...] in expression [do]  
    
       code  
    
    end

    Ruby for loop using range

    Example:

    a = gets.chomp.to_i   
    
    for i in 1..a do   
    
      puts i   
    
    end

    Output:

    Ruby for 1

    Ruby for loop using array

    Example:

    x = ["Blue", "Red", "Green", "Yellow", "White"]   
    
    for i in x do   
    
      puts i   
    
    end

    Output:

    Ruby for 2
  • Ruby Case Statement

    In Ruby, we use ‘case’ instead of ‘switch’ and ‘when’ instead of ‘case’. The case statement matches one statement with multiple conditions just like a switch statement in other languages.

    Syntax:

    case expression  
    
    [when expression [, expression ...] [then]  
    
       code ]...  
    
    [else  
    
       code ]  
    
    end

    Example:

    #!/usr/bin/ruby   
    
    print "Enter your day: "   
    
    day = gets.chomp   
    
    case day   
    
    when "Tuesday"   
    
      puts 'Wear Red or Orange'   
    
    when "Wednesday"   
    
      puts 'Wear Green'   
    
    when "Thursday"   
    
      puts 'Wear Yellow'   
    
     when "Friday"   
    
      puts 'Wear White'   
    
     when "Saturday"   
    
      puts 'Wear Black'   
    
    else   
    
      puts "Wear Any color"   
    
    end

    Output:

    Ruby switch 1

    Look at the above output, conditions are case sensitive. Hence, the output for ‘Saturday’ and ‘saturday’ are different.

  • Ruby If-else Statement

    The Ruby if else statement is used to test condition. There are various types of if statement in Ruby.

    • if statement
    • if-else statement
    • if-else-if (elsif) statement
    • ternay (shortened if statement) statement

    Ruby if statement

    Ruby if statement tests the condition. The if block statement is executed if condition is true.

    Syntax:

    if (condition)  
    
    //code to be executed  
    
    end
    Ruby if else 1

    Example:

    a = gets.chomp.to_i   
    
    if a >= 18   
    
      puts "You are eligible to vote."   
    
    end

    Output:

    Ruby if else 2

    Ruby if else

    Ruby if else statement tests the condition. The if block statement is executed if condition is true otherwise else block statement is executed.

    Syntax:

    if(condition)  
    
        //code if condition is true  
    
    else  
    
    //code if condition is false  
    
    end
    Ruby if else 3

    Example:

    a = gets.chomp.to_i   
    
    if a >= 18   
    
      puts "You are eligible to vote."   
    
    else   
    
      puts "You are not eligible to vote."   
    
    end

    Output:

    Ruby if else 4

    Ruby if else if (elsif)

    Ruby if else if statement tests the condition. The if block statement is executed if condition is true otherwise else block statement is executed.

    
    
    1. if(condition1)  
    2. //code to be executed if condition1is true  
    3. elsif (condition2)  
    4. //code to be executed if condition2 is true  
    5. else (condition3)  
    6. //code to be executed if condition3 is true  
    7. end 
    Ruby if else 5

    Example:

    a = gets.chomp.to_i   
    
    if a <50   
    
      puts "Student is fail"   
    
    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

    Output:

    Ruby if else 6

    Ruby ternary Statement

    In Ruby ternary statement, the if statement is shortened. First it evaluats an expression for true or false value then execute one of the statements.

    Syntax:

    1. test-expression ? iftrue-expression : iffalse-expression  

    Example:

    var = gets.chomp.to_i;   
    
    a = (var > 3 ? true : false);    
    
    puts a

    Output:

    Ruby if else 7
  • Ruby Data types

    Data types represents a type of data such as text, string, numbers, etc. There are different data types in Ruby:

    • Numbers
    • Strings
    • Symbols
    • Hashes
    • Arrays
    • Booleans

    Numbers

    Integers and floating point numbers come in the category of numbers.

    Integers are held internally in binary form. Integer numbers are numbers without a fraction. According to their size, there are two types of integers. One is Bignum and other is Fixnum.

    ClassDescriptionExample
    FixnumThey are normal numbers1
    BignumThey are big numbers111111111111
    FloatDecimal numbers3.0
    ComplexImaginary numbers4 + 3i
    RationalThey are fractional numbers9/4
    BigDecimalPrecision decimal numbers6.0

    Example:

    • In a calculation if integers are used, then only integers will be returned back.
    • In a calculation if float type is used, then only float will be returned back.
    • In case of dvision, following output will appear.

    Strings

    A string is a group of letters that represent a sentence or a word. Strings are defined by enclosing a text within single (‘) or double (“) quote.

    Example:

    • Two strings can be concatenated using + sign in between them.
    • Multiplying a number string with a number will repeat the string as many times.

    Symbols

    Symbols are like strings. A symbol is preceded by a colon (:). For example,
    Symbols are like strings. A symbol is preceded by a colon (:). For example,

    :abcd  

    They do not contain spaces. Symbols containing multiple words are written with (_). One difference between string and symbol is that, if text is a data then it is a string but if it is a code it is a symbol.

    Symbols are unique identifiers and represent static values, while string represent values that change.

    Example:

    Ruby Data types 6

    In the above snapshot, two different object_id is created for string but for symbol same object_id is created.


    Hashes

    A hash assign its values to its keys. They can be looked up by their keys. Value to a key is assigned by => sign. A key/value pair is separated with a comma between them and all the pairs are enclosed within curly braces. For example,

    {"Akash" => "Physics", "Ankit" => "Chemistry", "Aman" => "Maths"}

    Example:

    
    
    1. #!/usr/bin/ruby   
    2.   
    3. data = {"Akash" => "Physics", "Ankit" => "Chemistry", "Aman" => "Maths"}   
    4. puts data["Akash"]   
    5. puts data["Ankit"]   
    6. puts data["Aman"]

    Output:

    Ruby Data types 7

    Arrays

    An array stroes data or list of data. It can contain all types of data. Data in an array are separated by comma in between them and are enclosed by square bracket. For example,

    ["Akash", "Ankit", "Aman"]   

    Elements from an array are retrieved by their position. The position of elements in an array starts with 0.

    Example:

    #!/usr/bin/ruby   
    
      
    
    data = ["Akash", "Ankit", "Aman"]   
    
    puts data[0]   
    
    puts data[1]   
    
    puts data[2]

    Output:

    Ruby Data types 8