Blog

  •  Hashes

    A Hash is a collection of key-value pairs like this: “employee” = > “salary”. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

    The order in which you traverse a hash by either key or value may seem arbitrary and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil.

    Creating Hashes

    As with arrays, there is a variety of ways to create hashes. You can create an empty hash with the new class method −

    months = Hash.new
    

    You can also use new to create a hash with a default value, which is otherwise just nil −

    months = Hash.new( "month" )
    
    or
    
    months = Hash.new "month"
    

    When you access any key in a hash that has a default value, if the key or value doesn’t exist, accessing the hash will return the default value −

    #!/usr/bin/ruby
    
    months =Hash.new("month")
    
    puts "#{months[0]}"
    puts "#{months[72]}"

    This will produce the following result −

    month
    month
    
    #!/usr/bin/rubyH=Hash["a"=>100,"b"=>200]
    
    puts "#{H['a']}"
    puts "#{H['b']}"

    This will produce the following result −

    100
    200
    

    You can use any Ruby object as a key or value, even an array, so the following example is a valid one −

    [1,"jan"]=>"January"

    Hash Built-in Methods

    We need to have an instance of Hash object to call a Hash method. As we have seen, following is the way to create an instance of Hash object −

    Hash[[key =>|, value]*]orHash.new[or]Hash.new(obj)[or]Hash.new{|hash, key| block }

    This will return a new hash populated with the given objects. Now using the created object, we can call any available instance methods. For example −

    #!/usr/bin/ruby
    
    $,=", "
    months =Hash.new("month")
    months ={"1"=>"January","2"=>"February"}
    
    keys = months.keys
    puts "#{keys}"

    This will produce the following result −

    ["1", "2"]
    

    Following are the public hash methods (assuming hash is an array object) −

    Sr.No.Methods & Description
    1hash == other_hashTests whether two hashes are equal, based on whether they have the same number of key-value pairs, and whether the key-value pairs match the corresponding pair in each hash.
    2hash.[key]Using a key, references a value from hash. If the key is not found, returns a default value.
    3hash.[key] = valueAssociates the value given by value with the key given by key.
    4hash.clearRemoves all key-value pairs from hash.
    5hash.default(key = nil)Returns the default value for hash, nil if not set by default=. ([] returns a default value if the key does not exist in hash.)
    6hash.default = objSets a default value for hash.
    7hash.default_procReturns a block if hash was created by a block.
    8hash.delete(key) [or]array.delete(key) { |key| block }Deletes a key-value pair from hash by key. If block is used, returns the result of a block if pair is not found. Compare delete_if.
    9hash.delete_if { |key,value| block }Deletes a key-value pair from hash for every pair the block evaluates to true.
    10hash.each { |key,value| block }Iterates over hash, calling the block once for each key, passing the key-value as a two-element array.
    11hash.each_key { |key| block }Iterates over hash, calling the block once for each key, passing key as a parameter.
    12hash.each_key { |key_value_array| block }Iterates over hash, calling the block once for each key, passing the key and value as parameters.
    13hash.each_key { |value| block }Iterates over hash, calling the block once for each key, passing value as a parameter.
    14hash.empty?Tests whether hash is empty (contains no key-value pairs), returning true or false.
    15hash.fetch(key [, default] ) [or]hash.fetch(key) { | key | block }Returns a value from hash for the given key. If the key can’t be found, and there are no other arguments, it raises an IndexError exception; if default is given, it is returned; if the optional block is specified, its result is returned.
    16hash.has_key?(key) [or] hash.include?(key) [or]hash.key?(key) [or] hash.member?(key)Tests whether a given key is present in hash, returning true or false.
    17hash.has_value?(value)Tests whether hash contains the given value.
    18hash.index(value)Returns the key for the given value in hash, nil if no matching value is found.
    19hash.indexes(keys)Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select.
    20hash.indices(keys)Returns a new array consisting of values for the given key(s). Will insert the default value for keys that are not found. This method is deprecated. Use select.
    21hash.inspectReturns a pretty print string version of hash.
    22hash.invertCreates a new hash, inverting keys and values from hash; that is, in the new hash, the keys from hash become values and values become keys.
    23hash.keysCreates a new array with keys from hash.
    24hash.lengthReturns the size or length of hash as an integer.
    25hash.merge(other_hash) [or]hash.merge(other_hash) { |key, oldval, newval| block }Returns a new hash containing the contents of hash and other_hash, overwriting pairs in hash with duplicate keys with those from other_hash.
    26hash.merge!(other_hash) [or]hash.merge!(other_hash) { |key, oldval, newval| block }Same as merge, but changes are done in place.
    27hash.rehashRebuilds hash based on the current values for each key. If values have changed since they were inserted, this method reindexes hash.
    28hash.reject { |key, value| block }Creates a new hash for every pair the block evaluates to true
    29hash.reject! { |key, value| block }Same as reject, but changes are made in place.
    30hash.replace(other_hash)Replaces the contents of hash with the contents of other_hash.
    31hash.select { |key, value| block }Returns a new array consisting of key-value pairs from hash for which the block returns true.
    32hash.shiftRemoves a key-value pair from hash, returning it as a two-element array.
    33hash.sizeReturns the size or length of hash as an integer.
    34hash.sortConverts hash to a two-dimensional array containing arrays of key-value pairs, then sorts it as an array.
    35hash.store(key, value)Stores a key-value pair in hash.
    36hash.to_aCreates a two-dimensional array from hash. Each key/value pair is converted to an array, and all these arrays are stored in a containing array.
    37hash.to_hashReturns hash (self).
    38hash.to_sConverts hash to an array, then converts that array to a string.
    39hash.update(other_hash) [or]hash.update(other_hash) {|key, oldval, newval| block}Returns a new hash containing the contents of hash and other_hash, overwriting pairs in hash with duplicate keys with those from other_hash.
    40hash.value?(value)Tests whether hash contains the given value.
    41hash.valuesReturns a new array containing all the values of hash.
    42hash.values_at(obj, …)Returns a new array containing the values from hash that are associated with the given key or keys.

  • Arrays

    Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with and referred to by an index.

    Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array — that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

    Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid as arrays in other languages. Ruby arrays grow automatically while adding elements to them.

    Creating Arrays

    There are many ways to create or initialize an array. One way is with the new class method −

    names =Array.new

    You can set the size of an array at the time of creating array −

    names =Array.new(20)

    The array names now has a size or length of 20 elements. You can return the size of an array with either the size or length methods −

    #!/usr/bin/ruby
    
    names =Array.new(4,"mac")
    puts "#{names}"

    This will produce the following result −

    ["mac", "mac", "mac", "mac"]
    

    You can also use a block with new, populating each element with what the block evaluates to −

    #!/usr/bin/ruby
    
    nums =Array.new(10){|e| e = e *2}
    puts "#{nums}"

    This will produce the following result −

    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    

    There is another method of Array, []. It works like this −

    nums =Array.[](1,2,3,4,5)

    One more form of array creation is as follows −

    nums =Array[1,2,3,4,5]

    The Kernel module available in core Ruby has an Array method, which only accepts a single argument. Here, the method takes a range as an argument to create an array of digits −

    #!/usr/bin/ruby
    
    digits =Array(0..9)
    puts "#{digits}"

    This will produce the following result −

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Array Built-in Methods

    We need to have an instance of Array object to call an Array method. As we have seen, following is the way to create an instance of Array object −

    Array.[](...) [or] Array[...] [or] [...]
    

    This will return a new array populated with the given objects. Now, using the created object, we can call any available instance methods. For example −

    #!/usr/bin/ruby
    
    digits =Array(0..9)
    num = digits.at(6)
    puts "#{num}"

    This will produce the following result −

    6
    

    Following are the public array methods (assuming array is an array object) −

    Array pack Directives

    Following table lists the pack directives for use with Array#pack.

    Example

    Try the following example to pack various data.

    a =["a","b","c"]
    n =[65,66,67]
    puts a.pack("A3A3A3")#=> "a  b  c  "
    puts a.pack("a3a3a3")#=> "a\000\000b\000\000c\000\000"
    puts n.pack("ccc")#=> "ABC"

    This will produce the following result −

    a  b  c
    abc
    ABC

  • Strings

    A String object in Ruby holds and manipulates an arbitrary sequence of one or more bytes, typically representing characters that represent human language.

    The simplest string literals are enclosed in single quotes (the apostrophe character). The text within the quote marks is the value of the string −

    'This is a simple Ruby string literal'
    

    If you need to place an apostrophe within a single-quoted string literal, precede it with a backslash, so that the Ruby interpreter does not think that it terminates the string −

    'Won\'t you read O\'Reilly\'s book?'
    

    The backslash also works to escape another backslash, so that the second backslash is not itself interpreted as an escape character.

    Following are the string-related features of Ruby.

    Expression Substitution

    Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and } −

    #!/usr/bin/ruby
    
    x, y, z =12,36,72
    puts "The value of x is #{ x }."
    puts "The sum of x and y is #{ x + y }."
    puts "The average was #{ (x + y + z)/3 }."

    This will produce the following result −

    The value of x is 12.
    The sum of x and y is 48.
    The average was 40.
    

    General Delimited Strings

    With general delimited strings, you can create strings inside a pair of matching though arbitrary delimiter characters, e.g., !, (, {, <, etc., preceded by a percent character (%). Q, q, and x have special meanings. General delimited strings can be −

    %{Ruby is fun.}  equivalent to "Ruby is fun."
    %Q{ Ruby is fun. } equivalent to " Ruby is fun. "
    %q[Ruby is fun.]  equivalent to a single-quoted string
    %x!ls! equivalent to back tick command output ls
    

    Escape Characters

    Following table is a list of escape or non-printable characters that can be represented with the backslash notation.

    Character Encoding

    The default character set for Ruby is ASCII, whose characters may be represented by single bytes. If you use UTF-8, or another modern character set, characters may be represented in one to four bytes.

    You can change your character set using $KCODE at the beginning of your program, like this −

    $KCODE = 'u'
    

    Following are the possible values for $KCODE.

    String Built-in Methods

    We need to have an instance of String object to call a String method. Following is the way to create an instance of String object −

    new [String.new(str = "")]
    

    This will return a new string object containing a copy of str. Now, using str object, we can all use any available instance methods. For example −

    #!/usr/bin/ruby
    
    myStr =String.new("THIS IS TEST")
    foo = myStr.downcase
    
    puts "#{foo}"

    This will produce the following result −

    this is test
    

    Following are the public String methods ( Assuming str is a String object ) −

    String unpack Directives

    Following table lists the unpack directives for method String#unpack.

    Example

    Try the following example to unpack various data.

    "abc \0\0abc \0\0".unpack('A6Z6')#=> ["abc", "abc "]"abc \0\0".unpack('a3a3')#=> ["abc", " \000\000"]"abc \0abc \0".unpack('Z*Z*')#=> ["abc ", "abc "]"aa".unpack('b8B8')#=> ["10000110", "01100001"]"aaa".unpack('h2H2c')#=> ["16", "61", 97]"\xfe\xff\xfe\xff".unpack('sS')#=> [-2, 65534]"now = 20is".unpack('M*')#=> ["now is"]"whole".unpack('xax2aX2aX1aX2a')#=> ["h", "e", "l", "l", "o"]

  • Modules and Mixins

    Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.

    • Modules provide a namespace and prevent name clashes.
    • Modules implement the mixin facility.

    Modules define a namespace, a sandbox in which your methods and constants can play without having to worry about being stepped on by other methods and constants.

    Syntax

    module Identifier
       statement1
       statement2
       ...........
    end
    

    Module constants are named just like class constants, with an initial uppercase letter. The method definitions look similar, too: Module methods are defined just like class methods.

    As with class methods, 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.

    Example

    #!/usr/bin/ruby# Module defined in trig.rb filemoduleTrigPI=3.141592654defTrig.sin(x)# ..enddefTrig.cos(x)# ..endend

    We can define one more module with the same function name but different functionality −

    #!/usr/bin/ruby# Module defined in moral.rb filemoduleMoralVERY_BAD=0BAD=1defMoral.sin(badness)# ...endend

    Like class methods, whenever you define a method in a module, you specify the module name followed by a dot and then the method name.

    Ruby require Statement

    The require statement is similar to the include statement of C and C++ and the import statement of Java. If a third program wants to use any defined module, it can simply load the module files using the Ruby require statement −

    Syntax

    require filename
    

    Here, it is not required to give .rb extension along with a file name.

    Example

    $LOAD_PATH<<'.'require'trig.rb'require'moral'
    
    y =Trig.sin(Trig::PI/4)
    wrongdoing =Moral.sin(Moral::VERY_BAD)

    Here we are using $LOAD_PATH << ‘.’ to make Ruby aware that included files must be searched in the current directory. If you do not want to use $LOAD_PATH then you can use require_relative to include files from a relative directory.

    IMPORTANT − Here, both the files contain the same function name. So, this will result in code ambiguity while including in calling program but modules avoid this code ambiguity and we are able to call appropriate function using module name.

    Ruby include Statement

    You can embed a module in a class. To embed a module in a class, you use the include statement in the class −

    Syntax

    include modulename
    

    If a module is defined in a separate file, then it is required to include that file using require statement before embedding module in a class.

    Example

    Consider the following module written in support.rb file.

    module Week
       FIRST_DAY = "Sunday"
       def Week.weeks_in_month
    
      puts "You have four weeks in a month"
    end def Week.weeks_in_year
      puts "You have 52 weeks in a year"
    end end

    Now, you can include this module in a class as follows −

    #!/usr/bin/ruby
    $LOAD_PATH << '.'
    require "support"
    
    class Decade
    include Week
       no_of_yrs = 10
       def no_of_months
    
      puts Week::FIRST_DAY
      number = 10*12
      puts number
    end end d1 = Decade.new puts Week::FIRST_DAY Week.weeks_in_month Week.weeks_in_year d1.no_of_months

    This will produce the following result −

    Sunday
    You have four weeks in a month
    You have 52 weeks in a year
    Sunday
    120
    

    Mixins in Ruby

    Before going through this section, we assume you have the knowledge of Object Oriented Concepts.

    When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.

    Ruby does not support multiple inheritance directly but Ruby Modules have another wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.

    Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.

    Let us examine the following sample code to gain an understand of mixin −

    moduleAdefa1enddefa2endendmoduleBdefb1enddefb2endendclassSampleincludeAincludeBdefs1endend
    
    samp =Sample.new
    samp.a1
    samp.a2
    samp.b1
    samp.b2
    samp.s1
    

    Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus, you can say the class Sample shows multiple inheritance or a mixin.

  • Blocks

    You have seen how Ruby defines methods where you can put number of statements and then you call that method. Similarly, Ruby has a concept of Block.

    • A block consists of chunks of code.
    • You assign a name to a block.
    • The code in the block is always enclosed within braces ({}).
    • A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block.
    • You invoke a block by using the yield statement.

    Syntax

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

    Here, you will learn to invoke a block by using a simple yield statement. You will also learn to use a yield statement with parameters for invoking a block. You will check the sample code with both types of yield statements.

    The yield Statement

    Let’s look at an example of the yield statement −

    #!/usr/bin/rubydeftest
       puts "You are in the method"yield
       puts "You are again back to the method"yieldend
    test {puts "You are in the block"}

    This will produce the following result −

    You are in the method
    You are in the block
    You are again back to the method
    You are in the block
    

    You also can pass parameters with the yield statement. Here is an example −

    #!/usr/bin/rubydeftestyield5
       puts "You are in the method test"yield100end
    test {|i| puts "You are in the block #{i}"}

    This will produce the following result −

    You are in the block 5
    You are in the method test
    You are in the block 100
    

    Here, the yield statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block.

    Now, look at the following statement −

    test {|i| puts "You are in the block #{i}"}

    Here, the value 5 is received in the variable i. Now, observe the following puts statement −

    puts "You are in the block #{i}"

    The output of this puts statement is −

    You are in the block 5
    

    If you want to pass more than one parameters, then the yield statement becomes −

    yield a, b
    

    and the block is −

    test {|a, b| statement}

    The parameters will be separated by commas.

    Blocks and Methods

    You have seen how a block and a method can be associated with each other. You normally invoke a block by using the yield statement from a method that has the same name as that of the block. Therefore, you write −

    #!/usr/bin/rubydeftestyieldend
    test{ puts "Hello world"}

    This example is the simplest way to implement a block. You call the test block by using the yield statement.

    But if the last argument of a method is preceded by &, then you can pass a block to this method and this block will be assigned to the last parameter. In case both * and & are present in the argument list, & should come later.

    #!/usr/bin/rubydeftest(&block)
       block.call
    end
    test { puts "Hello World!"}

    This will produce the following result −

    Hello World!
    

    BEGIN and END Blocks

    Every Ruby source file can declare blocks of code to be run as the file is being loaded (the BEGIN blocks) and after the program has finished executing (the END blocks).

    #!/usr/bin/rubyBEGIN{# BEGIN block code 
       puts "BEGIN code block"}END{# END block code 
       puts "END code block"}# MAIN block code 
    puts "MAIN code block"

    A program may include multiple BEGIN and END blocks. BEGIN blocks are executed in the order they are encountered. END blocks are executed in reverse order. When executed, the above program produces the following result −

    BEGIN code block
    MAIN code block
    END code block

  • Methods

    Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

    Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly.

    Methods should be defined before calling them, otherwise Ruby will raise an exception for undefined method invoking.

    Syntax

    def method_name [( [arg [= default]]...[, * arg [, &expr ]])]
       expr..
    end
    

    So, you can define a simple method as follows −

    def method_name 
       expr..
    end
    

    You can represent a method that accepts parameters like this −

    def method_name (var1, var2)
       expr..
    end
    

    You can set default values for the parameters, which will be used if method is called without passing the required parameters −

    def method_name (var1 = value1, var2 = value2)
       expr..
    end
    

    Whenever you call the simple method, you write only the method name as follows −

    method_name
    

    However, when you call a method with parameters, you write the method name along with the parameters, such as −

    method_name 25, 30
    

    The most important drawback to using methods with parameters is that you need to remember the number of parameters whenever you call such methods. For example, if a method accepts three parameters and you pass only two, then Ruby displays an error.

    Example

    #!/usr/bin/rubydeftest(a1 ="Ruby", a2 ="Perl")
       puts "The programming language is #{a1}"
       puts "The programming language is #{a2}"end
    test "C","C++"
    test
    

    This will produce the following result −

    The programming language is C
    The programming language is C++
    The programming language is Ruby
    The programming language is Perl
    

    Return Values from Methods

    Every method in Ruby returns a value by default. This returned value will be the value of the last statement. For example −

    deftest
       i =100
       j =10
       k =0end

    This method, when called, will return the last declared variable k.

    Ruby return Statement

    The return statement in ruby is used to return one or more values from a Ruby Method.

    Syntax

    return [expr[`,' expr...]]
    

    If more than two expressions are given, the array containing these values will be the return value. If no expression given, nil will be the return value.

    Example

    returnORreturn12ORreturn1,2,3

    Have a look at this example −

    #!/usr/bin/rubydeftest
       i =100
       j =200
       k =300return i, j, k
    end
    var = test
    puts var
    

    This will produce the following result −

    100
    200
    300
    

    Variable Number of Parameters

    Suppose you declare a method that takes two parameters, whenever you call this method, you need to pass two parameters along with it.

    However, Ruby allows you to declare methods that work with a variable number of parameters. Let us examine a sample of this −

    #!/usr/bin/rubydefsample(*test)
       puts "The number of parameters is #{test.length}"for i in0...test.length
    
      puts "The parameters are #{test[i]}"endend
    sample "Zara","6","F" sample "Mac","36","M","MCA"

    In this code, you have declared a method sample that accepts one parameter test. However, this parameter is a variable parameter. This means that this parameter can take in any number of variables. So, the above code will produce the following result −

    The number of parameters is 3
    The parameters are Zara
    The parameters are 6
    The parameters are F
    The number of parameters is 4
    The parameters are Mac
    The parameters are 36
    The parameters are M
    The parameters are MCA
    

    Class Methods

    When a method is defined outside of the class definition, the method is marked as private by default. On the other hand, the methods defined in the class definition are marked as public by default. The default visibility and the private mark of the methods can be changed by public or private of the Module.

    Whenever you want to access a method of a class, you first need to instantiate the class. Then, using the object, you can access any member of the class.

    Ruby gives you a way to access a method without instantiating a class. Let us see how a class method is declared and accessed −

    classAccountsdefreading_chargeenddefAccounts.return_dateendend

    See how the method return_date is declared. It is declared with the class name followed by a period, which is followed by the name of the method. You can access this class method directly as follows −

    Accounts.return_date
    

    To access this method, you need not create objects of the class Accounts.

    Ruby alias Statement

    This gives alias to methods or global variables. Aliases cannot be defined within the method body. The alias of the method keeps the current definition of the method, even when methods are overridden.

    Making aliases for the numbered global variables (&dollar;1, &dollar;2,…) is prohibited. Overriding the built-in global variables may cause serious problems.

    Syntax

    alias method-name method-name
    alias global-variable-name global-variable-name
    

    Example

    alias foo bar
    alias &dollar;MATCH &dollar;&
    

    Here we have defined foo alias for bar, and &dollar;MATCH is an alias for &dollar;&

    Ruby undef Statement

    This cancels the method definition. An undef cannot appear in the method body.

    By using undef and alias, the interface of the class can be modified independently from the superclass, but notice it may be broke programs by the internal method call to self.

    Syntax

    undef method-name
    

    Example

    To undefine a method called bar do the following −

    undef bar
    

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