Category: Basic

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

    1. i = 1   
    2. while true   
    3.     if i*5 >= 25   
    4.         break   
    5.     end   
    6.     puts i*5   
    7.     i += 1   
    8. 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:

    1. for i in 5…11   
    2.    if i == 7 then   
    3.       next   
    4.    end   
    5.    puts i   
    6. end  

    Output:

    Ruby Break 2
  • 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:

    1. i = 10  #Here i is a variable.   
    2. 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:

    1. =begin  
    2.     This  
    3.     is  
    4.     multi line  
    5.     comment  
    6. =end  

    Example:

    1. =begin   
    2. we are declaring   
    3. a variable i   
    4. in this program   
    5. =end   
    6. i = 10   
    7. puts i  

    Output:

    Ruby Comments 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:

    1. case expression  
    2. [when expression [, expression …] [then]  
    3.    code ]…  
    4. [else  
    5.    code ]  
    6. end  

    Example:

    1. #!/usr/bin/ruby   
    2. print “Enter your day: ”   
    3. day = gets.chomp   
    4. case day   
    5. when “Tuesday”   
    6.   puts ‘Wear Red or Orange’   
    7. when “Wednesday”   
    8.   puts ‘Wear Green’   
    9. when “Thursday”   
    10.   puts ‘Wear Yellow’   
    11.  when “Friday”   
    12.   puts ‘Wear White’   
    13.  when “Saturday”   
    14.   puts ‘Wear Black’   
    15. else   
    16.   puts “Wear Any color”   
    17. end   

    Output:

    Ruby switch 1

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

  • Features of Ruby

    Ruby language has many features. Some of them are explained below:

    Features of Ruby
    • Object-oriented
    • Flexibility
    • Expressive feature
    • Mixins
    • Visual appearance
    • Dynamic typing and Duck typing
    • Exception handling
    • Garbage collector
    • Portable
    • Keywords
    • Statement delimiters
    • Variable constants
    • Naming conventions
    • Keyword arguments
    • Method names
    • Singleton methods
    • Missing method
    • Case Sensitive
  • Loops

    Loops in Ruby are used to execute the same block of code a specified number of times. This chapter details all the loop statements supported by Ruby.

    Ruby while Statement

    Syntax

    while conditional [do]
       code
    end
    

    Executes code while conditional is true. A while loop’s conditional is separated from code by the reserved word do, a newline, backslash \, or a semicolon ;.

    Example

    #!/usr/bin/ruby&dollar;i =0&dollar;num =5while&dollar;i <&dollar;num  do
       puts("Inside the loop i = #&dollar;i")&dollar;i &plus;=1end

    This will produce the following result −

    Inside the loop i = 0
    Inside the loop i = 1
    Inside the loop i = 2
    Inside the loop i = 3
    Inside the loop i = 4
    

    Ruby while modifier

    Syntax

    code while condition
    
    OR
    
    begin 
      code 
    end while conditional
    

    Executes code while conditional is true.

    If a while modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.

    Example

    #!/usr/bin/ruby&dollar;i =0&dollar;num =5begin
       puts("Inside the loop i = #&dollar;i")&dollar;i &plus;=1endwhile&dollar;i <&dollar;num
    

    This will produce the following result −

    Inside the loop i = 0
    Inside the loop i = 1
    Inside the loop i = 2
    Inside the loop i = 3
    Inside the loop i = 4
    

    Ruby until Statement

    until conditional [do]
       code
    end
    

    Executes code while conditional is false. An until statement’s conditional is separated from code by the reserved word do, a newline, or a semicolon.

    Example

    #!/usr/bin/ruby&dollar;i =0&dollar;num =5until&dollar;i >&dollar;num  do
       puts("Inside the loop i = #&dollar;i")&dollar;i &plus;=1;end

    This will produce the following result −

    Inside the loop i = 0
    Inside the loop i = 1
    Inside the loop i = 2
    Inside the loop i = 3
    Inside the loop i = 4
    Inside the loop i = 5
    

    Ruby until modifier

    Syntax

    code until conditional
    
    OR
    
    begin
       code
    end until conditional
    

    Executes code while conditional is false.

    If an until modifier follows a begin statement with no rescue or ensure clauses, code is executed once before conditional is evaluated.

    Example

    #!/usr/bin/ruby&dollar;i =0&dollar;num =5begin
       puts("Inside the loop i = #&dollar;i")&dollar;i &plus;=1;enduntil&dollar;i >&dollar;num
    

    This will produce the following result −

    Inside the loop i = 0
    Inside the loop i = 1
    Inside the loop i = 2
    Inside the loop i = 3
    Inside the loop i = 4
    Inside the loop i = 5
    

    Ruby for Statement

    Syntax

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

    Executes code once for each element in expression.

    Example

    #!/usr/bin/rubyfor i in0..5
       puts "Value of local variable is #{i}"end

    Here, we have defined the range 0..5. The statement for i in 0..5 will allow i to take values in the range from 0 to 5 (including 5). This will produce the following result −

    Value of local variable is 0
    Value of local variable is 1
    Value of local variable is 2
    Value of local variable is 3
    Value of local variable is 4
    Value of local variable is 5
    

    for…in loop is almost exactly equivalent to the following −

    (expression).each do |variable[, variable...]| code end
    

    except that a for loop doesn’t create a new scope for local variables. A for loop’s expression is separated from code by the reserved word do, a newline, or a semicolon.

    Example

    #!/usr/bin/ruby(0..5).eachdo|i|
       puts "Value of local variable is #{i}"end

    This will produce the following result −

    Value of local variable is 0
    Value of local variable is 1
    Value of local variable is 2
    Value of local variable is 3
    Value of local variable is 4
    Value of local variable is 5
    

    Ruby break Statement

    Syntax

    break
    

    Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil).

    Example

    #!/usr/bin/rubyfor i in0..5if i >2thenbreakend
       puts "Value of local variable is #{i}"end

    This will produce the following result −

    Value of local variable is 0
    Value of local variable is 1
    Value of local variable is 2
    

    Ruby next Statement

    Syntax

    next
    

    Jumps to the next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).

    Example

    #!/usr/bin/rubyfor i in0..5if i <2thennextend
       puts "Value of local variable is #{i}"end

    This will produce the following result −

    Value of local variable is 2
    Value of local variable is 3
    Value of local variable is 4
    Value of local variable is 5
    

    Ruby redo Statement

    Syntax

    redo
    

    Restarts this iteration of the most internal loop, without checking loop condition. Restarts yield or call if called within a block.

    Example

    #!/usr/bin/rubyfor i in0..5if i <2then
    
      puts "Value of local variable is #{i}"redoendend</pre>

    This will produce the following result and will go in an infinite loop −

    Value of local variable is 0
    Value of local variable is 0
    ............................
    

    Ruby retry Statement

    Syntax

    retry
    

    If retry appears in rescue clause of begin expression, restart from the beginning of the begin body.

    begin
       do_something # exception raisedrescue# handles errorretry# restart from beginningend

    If retry appears in the iterator, the block, or the body of the for expression, restarts the invocation of the iterator call. Arguments to the iterator is re-evaluated.

    for i in1..5retryif some_condition # restart from i == 1end

    Example

    #!/usr/bin/rubyfor i in0..5retryif i >2
    puts "Value of local variable is #{i}"end

    This will produce the following result and will go in an infinite loop −

    Value of local variable is 1
    Value of local variable is 2
    Value of local variable is 1
    Value of local variable is 2
    Value of local variable is 1
    Value of local variable is 2
    .................

  • if…else, case, unless


    Ruby offers conditional structures that are pretty common to modern languages. Here, we will explain all the conditional statements and modifiers available in Ruby.

    Ruby if…else Statement

    Syntax

    if conditional [then]
       code...

    [elsif conditional [then]

    code…]…

    [else
    code…]

    end

    if expressions are used for conditional execution. The values false and nil are false, and everything else are true. Notice Ruby uses elsif, not else if nor elif.

    Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.

    An if expression’s conditional is separated from code by the reserved word then, a newline, or a semicolon.

    Example

    #!/usr/bin/ruby
    
    x =1if x >2
       puts "x is greater than 2"elsif x <=2and x!=0
       puts "x is 1"else
       puts "I can't guess the number"end
    x is 1
    

    Ruby if modifier

    Syntax

    code if condition
    

    Executes code if the conditional is true.

    Example

    #!/usr/bin/ruby$debug=1
    print "debug\n"if$debug

    This will produce the following result −

    debug
    

    Ruby unless Statement

    Syntax

    unless conditional [then]
       code

    [else
    code ]

    end

    Executes code if conditional is false. If the conditional is true, code specified in the else clause is executed.

    Example

    #!/usr/bin/ruby

    x =1unless x>=2
    puts "x is less than 2"else
    puts "x is greater than 2"end

    This will produce the following result −

    x is less than 2
    

    Ruby unless modifier

    Syntax

    code unless conditional
    

    Executes code if conditional is false.

    Example

    #!/usr/bin/ruby$var=1
    print "1 -- Value is set\n"if$var
    print "2 -- Value is set\n"unless$var$var=false
    print "3 -- Value is set\n"unless$var

    This will produce the following result −

    1 -- Value is set
    3 -- Value is set
    

    Ruby case Statement

    Syntax

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

    [else
    code ]

    end

    Compares the expression specified by case and that specified by when using the === operator and executes the code of the when clause that matches.

    The expression specified by the when clause is evaluated as the left operand. If no when clauses match, case executes the code of the else clause.

    when statement’s expression is separated from code by the reserved word then, a newline, or a semicolon. Thus −

    case expr0
    when expr1, expr2
       stmt1
    when expr3, expr4
       stmt2
    else
       stmt3
    end
    

    is basically similar to the following −

    _tmp = expr0
    if expr1 === _tmp || expr2 === _tmp
       stmt1
    elsif expr3 === _tmp || expr4 === _tmp
       stmt2
    else
       stmt3
    end

    Example

    #!/usr/bin/ruby$age=5case$agewhen0..2
       puts "baby"when3..6
       puts "little child"when7..12
       puts "child"when13..18
       puts "youth"else
       puts "adult"end

    This will produce the following result −

    little child
    

  • Comments

    Comments are lines of annotation within Ruby code that are ignored at runtime. A single line comment starts with # character and they extend from # to the end of the line as follows −

    #!/usr/bin/ruby -w# This is a single line comment.
    
    puts "Hello, Ruby!"

    When executed, the above program produces the following result −

    Hello, Ruby!
    

    Ruby Multiline Comments

    You can comment multiple lines using =begin and =end syntax as follows −

    #!/usr/bin/ruby -w
    
    puts "Hello, Ruby!"=begin
    This is a multiline comment and con spwan as many lines as you
    like. But =begin and =end should come in the first line only. 
    =end

    When executed, the above program produces the following result −

    Hello, Ruby!
    

    Make sure trailing comments are far enough from the code and that they are easily distinguished. If more than one trailing comment exists in a block, align them. For example −

    @counter# keeps track times page has been hit@siteCounter# keeps track of times all pages have been hit

  • Operators

    Ruby supports a rich set of operators, as you’d expect from a modern language. Most operators are actually method calls. For example, a &plus; b is interpreted as a.&plus;(b), where the &plus; method in the object referred to by variable a is called with b as its argument.

    For each operator (&plus; – * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator (&plus;= -= etc.).

    Ruby Arithmetic Operators

    Assume variable a holds 10 and variable b holds 20, then −

    OperatorDescriptionExample
    &plus;Addition − Adds values on either side of the operator.a &plus; b will give 30
    Subtraction − Subtracts right hand operand from left hand operand.a – b will give -10
    *Multiplication − Multiplies values on either side of the operator.a * b will give 200
    /Division − Divides left hand operand by right hand operand.b / a will give 2
    %Modulus − Divides left hand operand by right hand operand and returns remainder.b % a will give 0
    **Exponent − Performs exponential (power) calculation on operators.a**b will give 10 to the power 20

    Ruby Comparison Operators

    Assume variable a holds 10 and variable b holds 20, then −

    OperatorDescriptionExample
    ==Checks if the value of two operands are equal or not, if yes then condition becomes true.(a == b) is not true.
    !=Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.(a != b) is true.
    >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(a > b) is not true.
    <Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(a < b) is true.
    >=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(a >= b) is not true.
    <=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(a <= b) is true.
    <=>Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second.(a <=> b) returns -1.
    ===Used to test equality within a when clause of a case statement.(1…10) === 5 returns true.
    .eql?True if the receiver and argument have both the same type and equal values.1 == 1.0 returns true, but 1.eql?(1.0) is false.
    equal?True if the receiver and argument have the same object id.if aObj is duplicate of bObj then aObj == bObj is true, a.equal?bObj is false but a.equal?aObj is true.

    Ruby Assignment Operators

    Assume variable a holds 10 and variable b holds 20, then −

    OperatorDescriptionExample
    =Simple assignment operator, assigns values from right side operands to left side operand.c = a &plus; b will assign the value of a &plus; b into c
    &plus;=Add AND assignment operator, adds right operand to the left operand and assign the result to left operand.c &plus;= a is equivalent to c = c &plus; a
    -=Subtract AND assignment operator, subtracts right operand from the left operand and assign the result to left operand.c -= a is equivalent to c = c – a
    *=Multiply AND assignment operator, multiplies right operand with the left operand and assign the result to left operand.c *= a is equivalent to c = c * a
    /=Divide AND assignment operator, divides left operand with the right operand and assign the result to left operand.c /= a is equivalent to c = c / a
    %=Modulus AND assignment operator, takes modulus using two operands and assign the result to left operand.c %= a is equivalent to c = c % a
    **=Exponent AND assignment operator, performs exponential (power) calculation on operators and assign value to the left operand.c **= a is equivalent to c = c ** a

    Ruby Parallel Assignment

    Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example −

    a = 10
    b = 20
    c = 30
    

    This may be more quickly declared using parallel assignment −

    a, b, c = 10, 20, 30
    

    Parallel assignment is also useful for swapping the values held in two variables −

    a, b = b, c
    

    Ruby Bitwise Operators

    Bitwise operator works on bits and performs bit by bit operation.

    Assume if a = 60; and b = 13; now in binary format they will be as follows −

     a    =  0011 1100
     b    =  0000 1101
     ------------------
     a&b  =  0000 1100
     a|b  =  0011 1101
     a^b  =  0011 0001
     ~a   =  1100 0011
    

    The following Bitwise operators are supported by Ruby language.

    OperatorDescriptionExample
    &Binary AND Operator copies a bit to the result if it exists in both operands.(a & b) will give 12, which is 0000 1100
    |Binary OR Operator copies a bit if it exists in either operand.(a | b) will give 61, which is 0011 1101
    ^Binary XOR Operator copies the bit if it is set in one operand but not both.(a ^ b) will give 49, which is 0011 0001
    ~Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.(~a ) will give -61, which is 1100 0011 in 2’s complement form due to a signed binary number.
    <<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.a << 2 will give 240, which is 1111 0000
    >>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.a >> 2 will give 15, which is 0000 1111

    Ruby Logical Operators

    The following logical operators are supported by Ruby language

    Assume variable a holds 10 and variable b holds 20, then −

    OperatorDescriptionExample
    andCalled Logical AND operator. If both the operands are true, then the condition becomes true.(a and b) is true.
    orCalled Logical OR Operator. If any of the two operands are non zero, then the condition becomes true.(a or b) is true.
    &&Called Logical AND operator. If both the operands are non zero, then the condition becomes true.(a && b) is true.
    ||Called Logical OR Operator. If any of the two operands are non zero, then the condition becomes true.(a || b) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.!(a && b) is false.
    notCalled Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.not(a && b) is false.

    Ruby Ternary Operator

    There is one more operator called Ternary Operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −

    OperatorDescriptionExample
    ? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

    Ruby Range Operators

    Sequence ranges in Ruby are used to create a range of successive values – consisting of a start value, an end value, and a range of values in between.

    In Ruby, these sequences are created using the “..” and “…” range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.

    OperatorDescriptionExample
    ..Creates a range from start point to end point inclusive.1..10 Creates a range from 1 to 10 inclusive.
    Creates a range from start point to end point exclusive.1…10 Creates a range from 1 to 9.

    Ruby defined? Operators

    defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined. It returns a description string of the expression, or nil if the expression isn’t defined.

    There are various usage of defined? Operator

    Usage 1

    defined? variable # True if variable is initialized

    For Example

    foo =42defined? foo    # => "local-variable"defined?$_# => "global-variable"defined? bar    # => nil (undefined)

    Usage 2

    defined? method_call # True if a method is defined

    For Example

    defined? puts        # => "method"defined? puts(bar)# => nil (bar is not defined here)defined? unpack      # => nil (not defined here)

    Usage 3

    # True if a method exists that can be called with super userdefined?super

    For Example

    defined?super# => "super" (if it can be called)defined?super# => nil (if it cannot be)

    Usage 4

    defined?yield# True if a code block has been passed

    For Example

    defined?yield# => "yield" (if there is a block passed)defined?yield# => nil (if there is no block)

    Ruby Dot “.” and Double Colon “::” Operators

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

    The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

    Remember in Ruby, classes and methods may be considered constants too.

    You need to just prefix the :: Const_name with an expression that returns the appropriate class or module object.

    If no prefix expression is used, the main Object class is used by default.

    Here are two examples −

    MR_COUNT=0# constant defined on main Object classmoduleFooMR_COUNT=0::MR_COUNT=1# set global count to 1MR_COUNT=2# set local count to 2end
    puts MR_COUNT# this is the global constant
    puts Foo::MR_COUNT# this is the local "Foo" constant

    Second Example

    CONST=' out there'classInside_oneCONST= proc {' in there'}defwhere_is_my_CONST::CONST+' inside one'endendclassInside_twoCONST=' inside two'defwhere_is_my_CONSTCONSTendend
    puts Inside_one.new.where_is_my_CONST
    puts Inside_two.new.where_is_my_CONST
    puts Object::CONST+Inside_two::CONST
    puts Inside_two::CONST+CONST
    puts Inside_one::CONST
    puts Inside_one::CONST.call +Inside_two::CONST

    Ruby Operators Precedence

    The following table lists all operators from highest precedence to lowest.

    MethodOperatorDescription
    Yes::Constant resolution operator
    Yes[ ] [ ]=Element reference, element set
    Yes**Exponentiation (raise to the power)
    Yes! ~ &plus; –Not, complement, unary plus and minus (method names for the last two are &plus;&commat; and -&commat;)
    Yes* / %Multiply, divide, and modulo
    Yes&plus; –Addition and subtraction
    Yes>> <<Right and left bitwise shift
    Yes&Bitwise ‘AND’
    Yes^ |Bitwise exclusive OR' and regular OR’
    Yes<= < > >=Comparison operators
    Yes<=> == === != =~ !~Equality and pattern match operators (!= and !~ may not be defined as methods)
     &&Logical ‘AND’
     ||Logical ‘OR’
     .. …Range (inclusive and exclusive)
     ? :Ternary if-then-else
     = %= { /= -= &plus;= |= &= >>= <<= *= &&= ||= **=Assignment
     defined?Check if specified symbol defined
     notLogical negation
     or andLogical composition

    NOTE − Operators with a Yes in the method column are actually methods, and as such may be overridden.

  • Variables, Constants

    Variables are the memory locations, which hold any data to be used by any program.

    There are five types of variables supported by Ruby. You already have gone through a small description of these variables in the previous chapter as well. These five types of variables are explained in this chapter.

    Ruby Global Variables

    Global variables begin with &dollar;. Uninitialized global variables have the value nil and produce warnings with the -w option.

    Assignment to global variables alters the global status. It is not recommended to use global variables. They make programs cryptic.

    Here is an example showing the usage of global variable.

    #!/usr/bin/ruby$global_variable=10classClass1defprint_global
    
      puts "Global variable in Class1 is #$global_variable"endendclassClass2defprint_global
      puts "Global variable in Class2 is #$global_variable"endend
    class1obj =Class1.new class1obj.print_global class2obj =Class2.new class2obj.print_global

    Here $global_variable is a global variable. This will produce the following result −

    NOTE − In Ruby, you CAN access value of any variable or constant by putting a hash (#) character just before that variable or constant.

    Global variable in Class1 is 10
    Global variable in Class2 is 10
    

    Ruby Instance Variables

    Instance variables begin with &commat;. Uninitialized instance variables have the value nil and produce warnings with the -w option.

    Here is an example showing the usage of Instance Variables.

    #!/usr/bin/rubyclassCustomerdefinitialize(id, name, addr)@cust_id= id
    
      @cust_name= name
      @cust_addr= addr
    enddefdisplay_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"endend# Create Objects
    cust1 =Customer.new("1","John","Wisdom Apartments, Ludhiya") cust2 =Customer.new("2","Poul","New Empire road, Khandala")# Call Methods cust1.display_details() cust2.display_details()

    Here, &commat;cust_id, &commat;cust_name and &commat;cust_addr are instance variables. This will produce the following result −

    Customer id 1
    Customer name John
    Customer address Wisdom Apartments, Ludhiya
    Customer id 2
    Customer name Poul
    Customer address New Empire road, Khandala
    

    Ruby Class Variables

    Class variables begin with &commat;&commat; and must be initialized before they can be used in method definitions.

    Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

    Overriding class variables produce warnings with the -w option.

    Here is an example showing the usage of class variable −

    #!/usr/bin/rubyclassCustomer@@no_of_customers=0definitialize(id, name, addr)@cust_id= id
    
      @cust_name= name
      @cust_addr= addr
    enddefdisplay_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"enddeftotal_no_of_customers()@@no_of_customers+=1
      puts "Total number of customers: #@@no_of_customers"endend# Create Objects
    cust1 =Customer.new("1","John","Wisdom Apartments, Ludhiya") cust2 =Customer.new("2","Poul","New Empire road, Khandala")# Call Methods cust1.total_no_of_customers() cust2.total_no_of_customers()

    Here &commat;&commat;no_of_customers is a class variable. This will produce the following result −

    Total number of customers: 1
    Total number of customers: 2
    

    Ruby Local Variables

    Local variables begin with a lowercase letter or _. The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block’s opening brace to its close brace {}.

    When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.

    Assignment to uninitialized local variables also serves as variable declaration. The variables start to exist until the end of the current scope is reached. The lifetime of local variables is determined when Ruby parses the program.

    In the above example, local variables are id, name and addr.

    Ruby Constants

    Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally.

    Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning.

    Open Compiler

    #!/usr/bin/rubyclassExampleVAR1=100VAR2=200defshow
    
      puts "Value of first Constant is #{VAR1}"
      puts "Value of second Constant is #{VAR2}"endend# Create Objects
    object =Example.new() object.show

    Here VAR1 and VAR2 are constants. This will produce the following result −

    Value of first Constant is 100
    Value of second Constant is 200
    

    Ruby Pseudo-Variables

    They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables.

    • self − The receiver object of the current method.
    • true − Value representing true.
    • false − Value representing false.
    • nil − Value representing undefined.
    • __FILE__ − The name of the current source file.
    • __LINE__ − The current line number in the source file.

    Ruby Basic Literals

    The rules Ruby uses for literals are simple and intuitive. This section explains all basic Ruby Literals.

    Integer Numbers

    Ruby supports integer numbers. An integer number can range from -230 to 230-1 or -262 to 262-1. Integers within this range are objects of class Fixnum and integers outside this range are stored in objects of class Bignum.

    You write integers using an optional leading sign, an optional base indicator (0 for octal, 0x for hex, or 0b for binary), followed by a string of digits in the appropriate base. Underscore characters are ignored in the digit string.

    You can also get the integer value, corresponding to an ASCII character or escape the sequence by preceding it with a question mark.

    Example

    123# Fixnum decimal1_234                # Fixnum decimal with underline-500# Negative Fixnum0377# octal0xff# hexadecimal0b1011               # binary?a                   # character code for 'a'?\n                  # code for a newline (0x0a)12345678901234567890# Bignum

    NOTE − Class and Objects are explained in a separate chapter of this tutorial.

    Floating Numbers

    Ruby supports floating numbers. They are also numbers but with decimals. Floating-point numbers are objects of class Float and can be any of the following −

    Example

    123.4# floating point value1.0e6# scientific notation4E20# dot not required4e+20# sign before exponential

    String Literals

    Ruby strings are simply sequences of 8-bit bytes and they are objects of class String. Double-quoted strings allow substitution and backslash notation but single-quoted strings don’t allow substitution and allow backslash notation only for \\ and \’

    Example

    #!/usr/bin/ruby -w
    
    puts 'escape using "\\"';
    puts 'That\'s right';

    This will produce the following result −

    escape using "\"
    That's right
    

    You can substitute the value of any Ruby expression into a string using the sequence #{ expr }. Here, expr could be any ruby expression.

    #!/usr/bin/ruby -w
    
    puts "Multiplication Value : #{24*60*60}";

    This will produce the following result −

    Multiplication Value : 86400
    

    Backslash Notations

    Following is the list of Backslash notations supported by Ruby −

    NotationCharacter represented
    \nNewline (0x0a)
    \rCarriage return (0x0d)
    \fFormfeed (0x0c)
    \bBackspace (0x08)
    \aBell (0x07)
    \eEscape (0x1b)
    \sSpace (0x20)
    \nnnOctal notation (n being 0-7)
    \xnnHexadecimal notation (n being 0-9, a-f, or A-F)
    \cx, \C-xControl-x
    \M-xMeta-x (c | 0x80)
    \M-\C-xMeta-Control-x
    \xCharacter x

    For more detail on Ruby Strings, go through Ruby Strings.

    Ruby Arrays

    Literals of Ruby Array are created by placing a comma-separated series of object references between the square brackets. A trailing comma is ignored.

    Example

    #!/usr/bin/ruby
    
    ary =["fred",10,3.14,"This is a string","last element",]
    ary.eachdo|i|
       puts i
    end

    This will produce the following result −

    fred
    10
    3.14
    This is a string
    last element
    

    For more detail on Ruby Arrays, go through Ruby Arrays.

    Ruby Hashes

    A literal Ruby Hash is created by placing a list of key/value pairs between braces, with either a comma or the sequence => between the key and the value. A trailing comma is ignored.

    Example

    #!/usr/bin/ruby
    
    hsh = colors ={"red"=>0xf00,"green"=>0x0f0,"blue"=>0x00f}
    hsh.eachdo|key, value|
       print key," is ", value,"\n"end

    This will produce the following result −

    red is 3840
    green is 240
    blue is 15
    

    For more detail on Ruby Hashes, go through Ruby Hashes.

    Ruby Ranges

    A Range represents an interval which is a set of values with a start and an end. Ranges may be constructed using the s..e and s…e literals, or with Range.new.

    Ranges constructed using .. run from the start to the end inclusively. Those created using … exclude the end value. When used as an iterator, ranges return each value in the sequence.

    A range (1..5) means it includes 1, 2, 3, 4, 5 values and a range (1…5) means it includes 1, 2, 3, 4 values.

    Example

    #!/usr/bin/ruby(10..15).eachdo|n| 
       print n,' 'end

    This will produce the following result −

    10 11 12 13 14 15
    

    For more detail on Ruby Ranges, go through Ruby Ranges.

  • Classes and Objects

    Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include −

    • Data Encapsulation
    • Data Abstraction
    • Polymorphism
    • Inheritance

    These features have been discussed in the chapter Object Oriented Ruby.

    An object-oriented program involves classes and objects. A class is the blueprint from which individual objects are created. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.

    Take the example of any vehicle. It comprises wheels, horsepower, and fuel or gas tank capacity. These characteristics form the data members of the class Vehicle. You can differentiate one vehicle from the other with the help of these characteristics.

    A vehicle can also have certain functions, such as halting, driving, and speeding. Even these functions form the data members of the class Vehicle. You can, therefore, define a class as a combination of characteristics and functions.

    A class Vehicle can be defined as −

    ClassVehicle{Number no_of_wheels
       Number horsepower
       Characters type_of_tank
       NumberCapacityFunction speeding {}Function driving {}Function halting {}}

    By assigning different values to these data members, you can form several instances of the class Vehicle. For example, an airplane has three wheels, horsepower of 1,000, fuel as the type of tank, and a capacity of 100 liters. In the same way, a car has four wheels, horsepower of 200, gas as the type of tank, and a capacity of 25 liters.

    Defining a Class in Ruby

    To implement object-oriented programming by using Ruby, you need to first learn how to create objects and classes in Ruby.

    A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. The class Customer can be displayed as −

    class Customer
    end
    

    You terminate a class by using the keyword end. All the data members in the class are between the class definition and the end keyword.

    Variables in a Ruby Class

    Ruby provides four types of variables −

    • Local Variables − Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _.
    • Instance Variables − Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (&commat;) followed by the variable name.
    • Class Variables − Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign &commat;&commat; and are followed by the variable name.
    • Global Variables − Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign (&dollar;).

    Example

    Using the class variable &commat;&commat;no_of_customers, you can determine the number of objects that are being created. This enables in deriving the number of customers.

    classCustomer&commat;&commat;no_of_customers =0end

    Creating Objects in Ruby using new Method

    Objects are instances of the class. You will now learn how to create objects of a class in Ruby. You can create objects in Ruby by using the method new of the class.

    The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods.

    Here is the example to create two objects cust1 and cust2 of the class Customer −

    cust1 =Customer.new
    cust2 =Customer.new

    Here, cust1 and cust2 are the names of two objects. You write the object name followed by the equal to sign (=) after which the class name will follow. Then, the dot operator and the keyword new will follow.

    Custom Method to Create Ruby Objects

    You can pass parameters to method new and those parameters can be used to initialize class variables.

    When you plan to declare the new method with parameters, you need to declare the method initialize at the time of the class creation.

    The initialize method is a special type of method, which will be executed when the new method of the class is called with parameters.

    Here is the example to create initialize method −

    classCustomer&commat;&commat;no_of_customers =0definitialize(id, name, addr)&commat;cust_id = id
    
      &amp;commat;cust_name = name
      &amp;commat;cust_addr = addr
    endend

    In this example, you declare the initialize method with id, name, and addr as local variables. Here, def and end are used to define a Ruby method initialize. You will learn more about methods in subsequent chapters.

    In the initialize method, you pass on the values of these local variables to the instance variables &commat;cust_id, &commat;cust_name, and &commat;cust_addr. Here local variables hold the values that are passed along with the new method.

    Now, you can create objects as follows −

    cust1 =Customer.new("1","John","Wisdom Apartments, Ludhiya")
    cust2 =Customer.new("2","Poul","New Empire road, Khandala")

    Member Functions in Ruby Class

    In Ruby, functions are called methods. Each method in a class starts with the keyword def followed by the method name.

    The method name always preferred in lowercase letters. You end a method in Ruby by using the keyword end.

    Here is the example to define a Ruby method −

    classSampledeffunction
    
      statement 1
      statement 2endend</pre>

    Here, statement 1 and statement 2 are part of the body of the method function inside the class Sample. These statments could be any valid Ruby statement. For example we can put a method puts to print Hello Ruby as follows −

    classSampledefhello
    
      puts "Hello Ruby!"endend</pre>

    Now in the following example, create one object of Sample class and call hello method and see the result −

    #!/usr/bin/rubyclassSampledefhello
    
      puts "Hello Ruby!"endend# Now using above class to create objects
    object =Sample.new object.hello

    This will produce the following result −

    Hello Ruby!
    

    Simple Case Study

    Here is a case study if you want to do more practice with class and objects.

    Ruby Class Case Study