Category: Ruby

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