Category: Basic

  • Syntax

    Let us write a simple program in ruby. All ruby files will have extension .rb. So, put the following source code in a test.rb file.

    #!/usr/bin/ruby -w
    
    puts "Hello, Ruby!";

    Here, we assumed that you have Ruby interpreter available in /usr/bin directory. Now, try to run this program as follows −

    $ ruby test.rb
    

    This will produce the following result −

    Hello, Ruby!
    

    You have seen a simple Ruby program, now let us see a few basic concepts related to Ruby Syntax.

    Whitespace in Ruby Program

    Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled.

    Example

    a + b is interpreted as a+b ( Here a is a local variable)
    a  +b is interpreted as a(+b) ( Here a is a method call)
    

    Line Endings in Ruby Program

    Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, −, or backslash at the end of a line, they indicate the continuation of a statement.

    Ruby Identifiers

    Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby.

    Ruby identifier names may consist of alphanumeric characters and the underscore character ( _ ).

    Reserved Words

    The following list shows the reserved words in Ruby. These reserved words may not be used as constant or variable names. They can, however, be used as method names.

    BEGINdonextthen
    ENDelseniltrue
    aliaselsifnotundef
    andendorunless
    beginensureredountil
    breakfalserescuewhen
    caseforretrywhile
    classifreturnwhile
    definself__FILE__
    defined?modulesuper__LINE__

    Here Document in Ruby

    “Here Document” refers to build strings from multiple lines. Following a << you can specify a string or an identifier to terminate the string literal, and all lines following the current line up to the terminator are the value of the string.

    If the terminator is quoted, the type of quotes determines the type of the line-oriented string literal. Notice there must be no space between << and the terminator.

    Here are different examples −

    #!/usr/bin/ruby -w
    
    print <<EOF
       This is the first way of creating
       here document ie. multiple line string.
    EOF
    
    print <<"EOF";# same as aboveThis is the second way of creating
       here document ie. multiple line string.EOF
    
    print <<EOC                 # execute commands
    	echo hi there
    	echo lo there
    EOC
    
    print <<"foo",<<"bar"# you can stack themI said foo.
    foo
    	I said bar.
    bar
    

    This will produce the following result −

       This is the first way of creating
       her document ie. multiple line string.
       This is the second way of creating
       her document ie. multiple line string.
    hi there
    lo there
    
      I said foo.
      I said bar.

    Ruby BEGIN Statement

    Syntax

    BEGIN {
       code
    }
    

    Declares code to be called before the program is run.

    Example

    #!/usr/bin/ruby
    
    puts "This is main Ruby Program"BEGIN{
       puts "Initializing Ruby Program"}

    This will produce the following result −

    Initializing Ruby Program
    This is main Ruby Program
    

    Ruby END Statement

    Syntax

    END {
       code
    }
    

    Declares code to be called at the end of the program.

    Example

    #!/usr/bin/ruby
    
    puts "This is main Ruby Program"END{
       puts "Terminating Ruby Program"}BEGIN{
       puts "Initializing Ruby Program"}

    This will produce the following result −

    Initializing Ruby Program
    This is main Ruby Program
    Terminating Ruby Program
    

    Ruby Comments

    A comment hides a line, part of a line, or several lines from the Ruby interpreter. You can use the hash character (#) at the beginning of a line −

    # I am a comment. Just ignore me.
    

    Or, a comment may be on the same line after a statement or expression −

    name = "Madisetti" # This is again comment
    

    You can comment multiple lines as follows −

    # This is a comment.
    # This is a comment, too.
    # This is a comment, too.
    # I said that already.
    

    Here is another form. This block comment conceals several lines from the interpreter with =begin/=end −

    =begin
    This is a comment.
    This is a comment, too.
    This is a comment, too.
    I said that already.
    =end
  • Environment Setup

    Local Environment Setup

    If you are still willing to set up your environment for Ruby programming language, then let’s proceed. This tutorial will teach you all the important topics related to environment setup. We would recommend you to go through the following topics first and then proceed further −

    • Ruby Installation on Linux/Unix − If you are planning to have your development environment on Linux/Unix Machine, then go through this chapter.
    • Ruby Installation on Windows − If you are planning to have your development environment on Windows Machine, then go through this chapter.
    • Ruby Command Line Options − This chapter list out all the command line options, which you can use along with Ruby interpreter.
    • Ruby Environment Variables − This chapter has a list of all the important environment variables to be set to make Ruby Interpreter works.

    Popular Ruby Editors

    To write your Ruby programs, you will need an editor −

    • If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus.
    • VIM (Vi IMproved) is a very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise, your can use your favorite vi editor to write Ruby programs.
    • RubyWin is a Ruby Integrated Development Environment (IDE) for Windows.
    • Ruby Development Environment (RDE) is also a very good IDE for windows users.

    Interactive Ruby (IRb)

    Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line.

    This tool comes along with Ruby installation so you have nothing to do extra to have IRb working.

    Just type irb at your command prompt and an Interactive Ruby Session will start as given below −

    $irb
    irb 0.6.1(99/09/16)
    irb(main):001:0>defhello
    irb(main):002:1> out ="Hello World"
    irb(main):003:1> puts out
    irb(main):004:1>endnil
    irb(main):005:0> hello
    HelloWorldnil
    irb(main):006:0>

    Do not worry about what we did here. You will learn all these steps in subsequent chapters.

    What is Next?

    We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs.

  • Overview

    Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan.

    You can find the name Yukihiro Matsumoto on the Ruby mailing list at www.ruby-lang.org. Matsumoto is also known as Matz in the Ruby community.

    Ruby is “A Programmer’s Best Friend”.

    Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is a perfect object-oriented language. Using Ruby syntax is much easier than using Smalltalk syntax.

    Features of Ruby

    • Ruby is an open-source and is freely available on the Web, but it is subject to a license.
    • Ruby is a general-purpose, interpreted programming language.
    • Ruby is a true object-oriented programming language.
    • Ruby is a server-side scripting language similar to Python and PERL.
    • Ruby can be used to write Common Gateway Interface (CGI) scripts.
    • Ruby can be embedded into Hypertext Markup Language (HTML).
    • Ruby has a clean and easy syntax that allows a new developer to learn very quickly and easily.
    • Ruby has similar syntax to that of many programming languages such as C++ and Perl.
    • Ruby is very much scalable and big programs written in Ruby are easily maintainable.
    • Ruby can be used for developing Internet and intranet applications.
    • Ruby can be installed in Windows and POSIX environments.
    • Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL.
    • Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase.
    • Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.

    Tools You Will Need

    For performing the examples discussed in this tutorial, you will need a latest computer like Intel Core i3 or i5 with a minimum of 2GB of RAM (4GB of RAM recommended). You also will need the following software −

    • Linux or Windows 95/98/2000/NT or Windows 7 operating system.
    • Apache 1.3.19-5 Web server.
    • Internet Explorer 5.0 or above Web browser.
    • Ruby 1.8.5

    This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Ruby. It also will talk about extending and embedding Ruby applications.

    What is Next?

    The next chapter guides you to where you can obtain Ruby and its documentation. Finally, it instructs you on how to install Ruby and prepare an environment to develop Ruby applications.

  • Ruby Tutorial

    What is Ruby?

    Ruby is an open-source and high-level programming language, which is known for its simplicity and developer-friendliness. This is designed by Yukihiro Matsumoto with the purpose of making programming more enjoyable and productive for developers. Ruby includes a lot of key features like its Object-Oriented, Dynamic Typing, Readable Syntax, and a large Standard Library collection.

    Why to Learn Ruby?

    Ruby is a simple and expressive programming language, which provides various advantages to programmers, especially in fields like web development, automation tasks, scripting, etc. Here in the following, we will discuss its features and advantages.

    • Simplicity and Readable Syntax: Ruby’s syntax is designed in a very clean and concise way, which provides easy-to-read, write, and understand code leading to increased productivity by allowing developers to focus more on problem-solving rather than complex syntax.
    • Powerful Frameworks: Ruby also provides popular web development frameworks like Ruby on Rails (RoR), which is a popular framework used for web development allowing developers to build complex applications more efficiently.
    • Strong Community and Ecosystem: Ruby also provides a supportive and active community, where users will find many libraries, tools, and resources. RubyGems repository offers a large set of collections of reusable code and libraries to accelerate development.
    • Prototyping: This is great for prototyping ideas and applications as its dynamic nature allows rapid iterations. This makes Ruby ideal for startups and developers.

    Characteristics of Ruby

    The following are important characteristics of Ruby programming:

    • Object-oriented:
      Ruby is purely object-oriented, which means everything in Ruby is an object including primitive data types like numbers, strings, and nil.
    • Dynamic Typing and Concise Syntax:
      In ruby, you don’t need to explicitly declare any variable types, it is automatically determined at runtime, providing greater flexibility and its syntax is to be designed clean, simple, and human-readable.
    • Automatic Memory Management (Garbage Collection):
      Ruby also provides flexibility by automatically managing memory allocation and deallocation with garbage collection, helping reduce complexity and the risk of memory leaks.
    • Large Standard Library:
      Ruby also has a large standard library consisting of many built-in classes and methods, covering a wide range of tasks like file I/O and data manipulation, etc.
    • Metaprogramming:
      It also allows to modify objects and classes during runtime. This provides flexibility as programs can dynamically be altered thus supporting Metaprogramming.

    Ruby Hello, World! Program

    To start with any programming, the very basic program is to print “Hello World!” Here we will print it in Ruby by using the puts. Below is an example of code to print “Hello, World!”. You can try it using the Edit & Run button.

    # Ruby code to print Hello, World!
    puts "Hello, World!"

    Ruby Online Compiler

    We provide an easy, user-friendly, and fast Ruby online compiler, where you can write, save, run, and share your Ruby programs. Click on this link to open it: Ruby Online Compiler

    Applications of Ruby

    Ruby is a general-purpose programming language, which has a wide range of applications that have been discussed in the given following.

    • Web and API Development:
      Ruby on Rails is one of the most popular frameworks for web development, where Rails is a full-stack web framework, which is used for building dynamic and database-driven websites. Example GitHub, Shopify, Airbnb, etc. Similarly, it is also commonly used for building RESTful APIs and web services. example Stripe and Twilio.
    • Scripting and Automation:
      Ruby’s concise syntax and rich libraries make it the best choice for creating command-line tools, scripting, and automating repetitive tasks like file manipulation, data processing, System administration and testing, etc.
    • Data Extraction and Analysis:
      Ruby’s powerful libraries like RMagick for image processing, Nokogiri for parsing HTML and XML, and HTTParty for making HTTP requests help in web scraping, data extraction, and analysis.
    • DevOps and System Administration:
      Ruby is also used in DevOps and system administration tasks, with tools like Chef (a configuration management tool) and Puppet, which are built using Ruby.
    • Application Development:
      Unlike C++ or Python, ruby can also used for developing various applications like game development, E-commerce Development, Social Media Platforms, etc.

    Jobs or Careers with Ruby

    Ruby’s nature of rapid development cycle, ease of use, and ability to handle interactions make it a great choice for site and application development, although it’s not used for large-scale platforms. Here in the following, we will discuss a few of its career options.

    • Ruby on Rails and Ruby Developer
    • Software Engineer
    • DevOps Engineer
    • Full-Stack Developer
    • Data Analyst/Scientist
    • Product and Community Manager
    • API Developer
    • Game Developer

    Target Audience: Who should Learn Ruby?

    This tutorial covers all key information from basic to advanced concepts related to Ruby scripting languages, which is useful for both aspiring and experienced programmers, web developers especially those who work with Ruby on Rails, Full-Stack Developers, also for Startups and Entrepreneurs as it allows for rapid development of web applications, Developers who interested in prototyping, test and driven developers and DevOps developers etc.

    Prerequisites to Learn Ruby

    Before you start practicing with various types of examples given in this tutorial, we are making an assumption that you are already aware of computer programs like basic computer literacy, basic knowledge of text editors and IDEs (like VS Code and Sublime Text, etc.), familiarity with version control system like git.