Author: Saim Khalid

  • 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
  • Ruby Variables

    Ruby variables are locations which hold data to be used in the programs. Each variable has a different name. These variable names are based on some naming conventions. Unlike other programming languages, there is no need to declare a variable in Ruby. A prefix is needed to indicate it.

    There are four types of variables in Ruby:

    • Local variables
    • Class variables
    • Instance variables
    • Global variables
    Ruby Variables

    Local variables

    A local variable name starts with a lowercase letter or underscore (_). It is only accessible or have its scope within the block of its initialization. Once the code block completes, variable has no scope.

    When uninitialized local variables are called, they are interpreted as call to a method that has no arguments.


    Class variables

    A class variable name starts with @@ sign. They need to be initialized before use. A class variable belongs to the whole class and can be accessible from anywhere inside the class. If the value will be changed at one instance, it will be changed at every instance.

    A class variable is shared by all the descendents of the class. An uninitialized class variable will result in an error.

    Example:

    #!/usr/bin/ruby   
    
      
    
    class States   
    
       @@no_of_states=0   
    
       def initialize(name)   
    
          @states_name=name   
    
          @@no_of_states += 1   
    
       end   
    
       def display()   
    
         puts "State name #@state_name"   
    
        end   
    
        def total_no_of_states()   
    
           puts "Total number of states written: #@@no_of_states"   
    
        end   
    
    end   
    
      
    
    # Create Objects   
    
    first=States.new("Assam")   
    
    second=States.new("Meghalaya")   
    
    third=States.new("Maharashtra")   
    
    fourth=States.new("Pondicherry")   
    
      
    
    # Call Methods   
    
    first.total_no_of_states()   
    
    second.total_no_of_states()   
    
    third.total_no_of_states()   
    
    fourth.total_no_of_states()

    In the above example, @@no_of_states is a class variable.

    Output:

    Ruby variables 1

    Instance variables

    An instance variable name starts with a @ sign. It belongs to one instance of the class and can be accessed from any instance of the class within a method. They only have limited access to a particular instance of a class.

    They don’t need to be initialize. An uninitialized instance variable will have a nil value.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2.   
    3. class States   
    4.    def initialize(name)   
    5.       @states_name=name   
    6.    end   
    7.    def display()   
    8.       puts "States name #@states_name"   
    9.     end   
    10. end   
    11.   
    12. # Create Objects   
    13. first=States.new("Assam")   
    14. second=States.new("Meghalaya")   
    15. third=States.new("Maharashtra")   
    16. fourth=States.new("Pondicherry")   
    17.   
    18. # Call Methods   
    19. first.display()   
    20. second.display()   
    21. third.display()   
    22. fourth.display()

    In the above example, @states_name is the instance variable.

    Output:

    Ruby variables 2

    Global variables

    A global variable name starts with a $ sign. Its scope is globally, means it can be accessed from any where in a program.

    An uninitialized global variable will have a nil value. It is advised not to use them as they make programs cryptic and complex.

    There are a number of predefined global variables in Ruby.

    Example:

    
    
    1. #!/usr/bin/ruby   
    2.   
    3. $global_var = "GLOBAL"   
    4. class One   
    5.   def display   
    6.      puts "Global variable in One is #$global_var"   
    7.   end   
    8. end   
    9. class Two   
    10.   def display   
    11.      puts "Global variable in Two is #$global_var"   
    12.   end   
    13. end   
    14.   
    15. oneobj = One.new   
    16. oneobj.display   
    17. twoobj = Two.new   
    18. twoobj.display

    In the above example, @states_name is the instance variable.

    Output:

    Ruby variables 3

    Summary

    LocalGlobalInstanceClass
    ScopeLimited within the block of initialization.Its scope is globally.It belongs to one instance of a class.Limited to the whole class in which they are created.
    NamingStarts with a lowercase letter or underscore (_).Starts with a $ sign.Starts with an @ sign.Starts with an @@ sign.
    InitializationNo need to initialize. An uninitialized local variable is interpreted as methods with no arguments.No need to initialize. An uninitialized global variable will have a nil value.No need to initialize. An uninitialized instance variable will have a nil value.They need to be initialized before use. An uninitialized global variable results in an error.
  • Ruby Operators

    Ruby has a built-in modern set of operators. Operators are a symbol which is used to perform different operations. For example, +, -, /, *, etc.


    Types of operators:

    • Unary operator
    • Airthmetic operator
    • Bitwise operator
    • Logical operator
    • Ternary operator
    • Assignment operator
    • Comparison operator
    • Range operator

    Unary Operator

    Unary operators expect a single operand to run on.

    OperatorDescription
    !Boolean NOT
    ~Bitwise complement
    +Unary plus

    Example

    In file hello.rb, write the following code.

    #!/usr/bin/ruby -w   
    
       
    
     puts("Unary operator")   
    
     puts(~5)   
    
     puts(~-5)   
    
     puts(!true)   
    
     puts(!false)

    Output:

    Ruby operators 1

    Airthmetic Operator

    Airthmetic operators take numerical values as operands and return them in a single value.

    OperatorDescription
    +Adds values from both sides of the operator.
    Subtract values from both sides of the operator.
    /Divide left side operand with right side operand.
    *Multiply values from both sides of the operator.
    **Right side operand becomes the exponent of left side operand.
    %Divide left side operand with right side operand returning remainder.

    Example

    In file hello.rb, write the following code.

    #!/usr/bin/ruby -w   
    
      
    
     puts("add operator")   
    
     puts(10 + 20)      
    
     puts("subtract operator")   
    
     puts(35 - 15)    
    
     puts("multiply operator")   
    
     puts(4 * 8)   
    
     puts("division operator")   
    
     puts(25 / 5)   
    
     puts("exponential operator")   
    
     puts(5 ** 2)   
    
     puts("modulo operator")   
    
     puts(25 % 4)

    Output:

    Ruby operators 2

    Bitwise Operator

    Bitwise operators work on bits operands.

    OperatorDescription
    &AND operator
    |OR operator
    <<Left shift operator
    >>Right shift operator
    ^XOR operator
    ~Complement operator

    Logical Operator

    Logical operators work on bits operands.

    OperatorDescription
    &&AND operator
    ||OR operator

    Ternary Operator

    Ternary operators first check whether given conditions are true or false, then execute the condition.

    OperatorDescription
    ?:Conditional expression

    Example

    In file hello.rb, write the following code.

    #!/usr/bin/ruby -w   
    
       
    
     puts("Ternary operator")   
    
     puts(2<5 ? 5:2)   
    
     puts(5<2 ? 5:2)

    Output:

    Ruby operators 3

    Assignment Operator

    Assignment operator assign a value to the operands.

    OperatorDescription
    =Simple assignment operator
    +=Add assignment operator
    -=subtract assignment operator
    *=Multiply assignment operator
    /=Divide assignment operator
    %=Modulus assignment operator
    **=Exponential assignment operator

    Comparison Operator

    Comparison operators compare two operands.

    OperatorDescription
    ==Equal operator
    !=Not equal operator
    >left operand is greater than right operand
    <Right operand is greater than left operand
    >=Left operand is greater than or equal to right operand
    <=Right operand is greater than or equal to left operand
    <=>Combined comparison operator
    .eql?Checks for equality and type of the operands
    equal?Checks for the object ID

    Example

    In file hello.rb, write the following code.

    #!/usr/bin/ruby -w   
    
       
    
     puts("Comparison operator")   
    
     puts(2 == 5)   
    
     puts(2 != 5)   
    
     puts(2 > 5)   
    
     puts(2 < 5)   
    
     puts(2 >= 5)   
    
     puts(2 <= 5)

    Output:

    Ruby operators 4

    Range Operator

    Range operators create a range of successive values consisting of a start, end and range of values in between.

    The (..) creates a range including the last term and (…) creates a range excluding the last term.

    For example, for the range of 1..5, output will range from 1 to 5.

    and for the range of 1…5, output will range from 1 to 4.

    OperatorDescription
    ..Range is inclusive of the last term
    Range is exclusive of the last term
  • Hello Ruby Program

    Now we will write a simple program of Ruby. Before writing Hello World program, we are assuming that you have successfully installed Ruby in your system.


    Requirement for Hello Ruby Program

    • Download Ruby and install it.
    • Create a file with .rb extension.
    • Connect Ruby path to the file.
    • Run the file.

    Creating Hello Ruby Program

    1) Use any text editor and create a hello.rb file. Write the following code,

    puts "Hello Ruby !"  

    2) Connect Ruby path to the above file. We have created hello.rb file in the Desktop. So first we need to go the Desktop directory through our console.

    Ruby Hello ruby program 1

    3) Run the following command.

    ruby hello.rb  
    Ruby Hello ruby program 2

    This is final output of our Hello Ruby program.

  • Ruby Installation

    Ruby is a cross platform programming language. It is installed differently on different operating systems.

    • For UNIX like operating system, use your system’s package manager.
    • For Windows operating system, use RubyInstaller.
    • For OS X system, use third party tools (rbenv and RVM).

    We will install Ruby on Linux Ubuntu using package manager.

    Step 1 Choose the package management system which you want to install from the link 

    Step 2 Debian GNU/Linux and Ubuntu use the apt package manager. Use the following command:

    1. sudo apt-get install ruby-full  

    Here, by default, the ruby-full package provides Ruby 1.9.3 version which is an old version on Debian and Ubuntu.

    Ruby installation 1

    Step 3 To know your Ruby version installed in your system, use the command,

    1. ruby -v  
    Ruby installation 2
  • Ruby vs Python

    Similarities

    • They both are high level language.
    • They both are server side scripting language.
    • Both are used for web applications.
    • Both work on multiple platforms.
    • Both have clean syntax and are easily readable.
    • Both use an interactive prompt called irb.
    • Objects are strongly and dynamically typed.
    • Both use embedded doc tools.

    Differences

    TermsRubyPython
    DefinitionRuby is an open source web application programming language.Python is a high level programming language.
    Object OrientedFully object oriented programming language.Not fully object oriented programming language.
    DeveloperYukihiro Matsumoto in 1990s.Guido Van Rossum in 1980s.
    Developing EnvironmentEclipseIDE is supported.multiple IDEs are supported.
    LibrariesIt has smaller library than Python.Has larger range of libraries.
    MixinsMixins are used.Mixins can’t be used.
    Web frameworksRuby on RailsDjango
    CommunityMainly focused on web.Focussed in academia and Linux.
    UsageApple Github Twitter Groupon Shopify ThemeForestGoogle Instagram Mozilla Firefox The Washington post Yahoo Shopzilla
    Built-in classesBuilt-in classes can be modifiedBuilt-in classes can’t be modified
    elseifelsifelif
    Unset a variableOnce a variable is set you can’t unset it back . It will be present in the symbol table as long as it is in scope.del statement help you to delete a set variable.
    yield keywordIt will execute another function that has been passed as the final argument, then immediately resume.It returns execution to the scope outside the function’s invocation. External code is responsible for resuming the function.
    Anonymous functionsSupport blocks, procs and lambdas.Support only lambdas.
    FunctionsDoesn’t have functions.It has functions.
    TuplesIt doesn’t support tuples.It support tuples.
    switch/case statementIt support switch/case statement.It doesn’t support switch/case statement.
    lambda functionIts lambda functions are larger.It support only single line lambda function.
    InheritanceSupport single inheritance.Support multiple inheritance.