Category: Ruby

  • Ruby Operators

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


    Types of operators:

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

    Unary Operator

    Unary operators expect a single operand to run on.

    OperatorDescription
    !Boolean NOT
    ~Bitwise complement
    +Unary plus

    Example

    In file hello.rb, write the following code.

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

    Output:

    Ruby operators 1

    Airthmetic Operator

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

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

    Example

    In file hello.rb, write the following code.

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

    Output:

    Ruby operators 2

    Bitwise Operator

    Bitwise operators work on bits operands.

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

    Logical Operator

    Logical operators work on bits operands.

    OperatorDescription
    &&AND operator
    ||OR operator

    Ternary Operator

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

    OperatorDescription
    ?:Conditional expression

    Example

    In file hello.rb, write the following code.

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

    Output:

    Ruby operators 3

    Assignment Operator

    Assignment operator assign a value to the operands.

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

    Comparison Operator

    Comparison operators compare two operands.

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

    Example

    In file hello.rb, write the following code.

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

    Output:

    Ruby operators 4

    Range Operator

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

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

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

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

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

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


    Requirement for Hello Ruby Program

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

    Creating Hello Ruby Program

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

    puts "Hello Ruby !"  

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

    Ruby Hello ruby program 1

    3) Run the following command.

    ruby hello.rb  
    Ruby Hello ruby program 2

    This is final output of our Hello Ruby program.

  • Ruby Installation

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

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

    We will install Ruby on Linux Ubuntu using package manager.

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

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

    1. sudo apt-get install ruby-full  

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

    Ruby installation 1

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

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

    Similarities

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

    Differences

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

  • 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

    Object Oriented

    Ruby is purely object oriented programming language. Each and every value is an object. Every object has a class and every class has a super class. Every code has their properties and actions. Ruby is influenced with Smalltalk language. Rules applying to objects applies to the entire Ruby.


    Flexibility

    Ruby is a flexible language as you can easily remove, redefine or add existing parts to it. It allows its users to freely alter its parts as they wish.


    Mixins

    Ruby has a feature of single inheritance only. Ruby has classes as well as modules. A module has methods but no instances. Instead, a module can be mixed into a class, which adds the method of that module to the class. It is similar to inheritance but much more flexible.


    Visual appearance

    Ruby generally prefers English keyword and some punctuation is used to decorate Ruby. It doesn’t need variable declaration.


    Dynamic typing and Duck typing

    Ruby is a dynamic programming language. Ruby programs are not compiled. All class, module and method definition are built by the code when it run.

    Ruby variables are loosely typed language, which means any variable can hold any type of object. When a method is called on an object, Ruby only looks up at the name irrespective of the type of object. This is duck typing. It allows you to make classes that pretend to be other classes.


    Variable constants

    In Ruby, constants are not really constant. If an already initialized constant will be modified in a script, it will simply trigger a warning but will not halt your program.


    Naming conventions

    Ruby defines some naming conventions for its variable, method, constant and class.

    • Constant: Starts with a capital letter.
    • Global variable: Starts with a dollar sign ($).
    • Instance variable: Starts with a (@) sign.
    • Class variable: Starts with a (@@) sign.
    • Method name: Allowed to start with a capital letter.

    Keyword arguments

    Like Python, Ruby methods can also be defined using keyword arguments.


    Method names

    Methods are allowed to end with question mark (?) or exclamation mark (!). By convention, methods that answer questions end with question mark and methods that indicates that method can change the state of the object end with exclamation mark.


    Singleton methods

    Ruby singleton methods are per-object methods. They are only available on the object you defined it on.


    Missing method

    If a method is lost, Ruby calls the method_missing method with name of the lost method.


    Statement delimiters

    Multiple statements in a single line must contain semi colon in between but not at the end of a line.


    Keywords

    In Ruby there are approximately 42 keywords which can’t be used for other purposes. They are called reserved words.


    Case Sensitive

    Ruby is a case-sensitive language. Lowercase letters and uppercase letters are different.

  • What is Ruby

    Ruby is a dynamic, open source, object oriented and reflective programming language. Ruby is considered similar to Perl and Smalltalk programming languages. It runs on all types of platforms like Windows, Mac OS and all versions of UNIX.

    It is fully object oriented programming language. Everything is an object in Ruby. Each and every code has their properties and actions. Here properties refer to variables and actions refer to methods.

    Ruby is considered to follow the principle of POLA (principle of least astonishment). It means that the language behaves in such a way to minimize the confusion for experienced users.


    History of Ruby

    Ruby is designed and developed by Yukihiro “Martz” Matsumoto in mid 1990s in Japan.


    Idea of Ruby

    Perl is a scripting language but comes under the category of Toy language. Python is not fully object oriented language. Ruby developer Yukihiro “Martz” Matsumoto wanted a programming language which is completely object oriented and should be easy to use as a scripting language. He searched for this type of language, but couldn’t find one. Hence, he developed one.


    The name “Ruby”

    The name “Ruby” originated during a chat session between Matsumoto and Keiju Ishitsuka. Two names were selected, “Coral” and “Ruby”. Matsumoto chose the later one as it was the birthstone of one of his colleagues.


    Ruby Early Years

    The first public release of Ruby 0.95 was announced on Japanese newspaper on December 21, 1995. Within next two days, three more versions were released.

    Ruby was localized to Japan. To expand it, the Ruby-Talk, first English language Ruby mailing list was created.

    In 2001, first Ruby book “Programming Ruby” was published. After its publishment, learners of Ruby throughout the world increased.

    In 2005, they released their first Ruby framework “Ruby on Rails”. The framework release was a big success and the Ruby community increased incredibly.

    Ruby 1.8.7 was released in May 2008. At this point, Ruby was at its peak so much that even Mac OS X began their shipping with built-in Ruby.


    Ruby in Present

    The current Ruby version 2.4.0 was released on Christmas in 2016. It has several new features like improvement to hash table, instance variable access, Array#max and Array#min.


    Future of Ruby

    Ruby is a great object oriented scripting programming language. Looking at its past we can say that it has a bright future if its community members continue expanding it beyond the thinking.


    Ruby Versions

    There are many Ruby versions that have been released till date. Current stable Ruby version is 2.4

    • Version 1.8 (4th Aug, 2003)
    • Version 1.9 (25th Dec, 2007)
    • Version 2.0 (24th Feb, 2013)
    • Version 2.1 (25th Dec, 2013)
    • Version 2.2 (25th Dec, 2014)
    • Version 2.3 (25th Dec, 2015)
    • Version 2.4 (25th Dec, 2016)
    • Version 3.0 (Future Release)
  • Ruby Tutorial

    Ruby tutorial provides basic and advanced concepts of Ruby. Our Ruby programming tutorial is designed for beginners and professionals both.

    Ruby is an open-source and fully object-oriented programming language.

    Our Ruby tutorial includes all topics of Ruby such as installation, example, operators, control statements, loops, comments, arrays, strings, hashes, regular expressions, file handling, exception handling, OOPs, Ranges, Iterators. etc