A Comprehensive Guide to Programming in Ruby

0
4115

This article gives readers Ruby in a nutshell, covering all aspects of how to program in it. Enthusiasts can then get started on it quickly.

Ruby is a cross-platform language, and like Java, it is also an OOP (object-oriented programming) language. It is a general-purpose scripting language, which is dynamic, powerful, easy-to-use and reflective.

You can use Ruby as a flexible programming language for the following:

  • Developing Web applications
  • Processing text
  • Developing games
  • With Ruby, you can perform the following tasks:
  • Write Common Gateway Interface (CGI) scripts
  • Embed it into Hypertext Markup Language (HTML)
  • Develop Internet and intranet applications
  • Install it in Windows and POSIX environments
  • Connect to PostgreSQL, DB2, MySQL, Oracle, Sybase and others
  • Support many GUI tools such as Tcl/Tk, GTK and OpenGL
  • Make Web applications using Ruby on Rails, Sinatra or other frameworks

Quick facts

  • Developed by: Japanese computer scientist and software programmer, Yukihiro Matsumoto (Matz), in 1993
  • Platforms supported: Windows, Mac OS, and the various versions of *NIX
  • Used by Amazon, BBC, Cisco, CNET, IBM, JP Morgan, NASA, Yahoo and many others

Rails and Rspec

Users can use the Ruby programming language to design and build higher level, domain specific languages or DSLs like Rails and Rspec.

Rails: Ruby on Rails, or just Rails, is a server-side Web application framework written in Ruby. It is released under the MIT licence. Rails is a model–view–controller (MVC) framework that provides users with default structures/scaffolds for creating Web services or pages, and even for connecting to databases.

RSpec: RSpec has been written in Ruby. It is a unit test framework and is used to test the behaviour of an application. The focus is not on how the application works but on what it does.

Basic syntax

Ruby is a free format language, which means you can write code anywhere, in any line or column, without writing a main method/function.

Naming conventions

  • Variable, file and directory names should be in snake case and lower case. Example: num_name.
  • Constants should be in snake case and upper case. Example: NUMBER\_OF\_RECORDS.
  • Ruby source code files should have an extension .rb. Example: file1.rb.
  • Class and module names should be in camel case. Example: MyFirstClass.
  • Variable names are case sensitive.

You can refer to the website for more information on the Ruby style guide.

Comments

  • Single-line comments should be prefixed by an unquoted pound sign (#).
  • Multi-line comments should be enclosed within =begin and =end.

Statement delimiters

Use a semicolon (;) to separate the multiple statements included in a single line.

Basic data types

Integers

  • Numbers without a decimal point
  • Small numbers or Fixnum. Example: 1, 3, -10004
  • Big numbers or Bignum. Example: 49349443040329402394302483298439

Float

  • Numbers with decimal points. Example: 0.4, 100.5

Strings

  • This is an object that can comprise one or more bytes arranged in a random sequence, which usually represents characters, words or phrases. Example: “I am excited to learn Ruby!”

Boolean

  • Boolean holds two values — true and false.

nil

  • This is a keyword as well as an object, and it represents ‘nothing’.

You will learn about a few other such data types as we explore other topics.

Operators and the input statement

Variable scope in Ruby: A scope helps you understand that part of the program in which there is a variable, beyond which it is not accessible.

  • Global, class, instance and local are four different types of variable scopes in the Ruby program.
  • You can identify a Ruby variable by the first character, which denotes the scope of the variable.

More about the types of scope will be discussed later in this article, when exploring ‘class’.

Arithmetic operators and string arithmetic

Arithmetic operators: There are six arithmetic operators:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Exponentiation (**)
  • Modulo (%).
  • Here is an example.
  • Exponentiation: 3**3 is 27
  • Modulo 25 % 8 would be 1

String arithmetic: Strings can be used with arithmetic operators. For example:

  • puts ‘I like’ + ‘Ruby programming.’ will concatenate the strings displaying the output as ‘I like Ruby programming’.
  • puts like ‘Ruby ‘ * 5’ will print Ruby five times.

Comparison operators: Ruby provides many comparison operators to check the equality between two values. These are shown below:

== Tests for equality
.eql? Same as ==
!= Tests for inequality
< Less than
>Greater than
>= Greater than/equal to
<= Less than/equal to
<=> Combined comparison operator

Conversions:

  • The string version of an object can be acquired by adding ‘.to_s’ after the object.
  • The integer version of an object can be acquired by adding ‘.to_i’ after the object.
  • The float version of an object can be derived by adding ‘.to_f’ after the object.

An example is shown below:

num1 = 3

num2 = ‘15’

puts num1.to_s + num2

puts num1 + num2.to_i

Output:

315

18

Getting user inputs: The user input in a Ruby program can be acquired by using ‘gets’, as shown below:

puts ‘Enter your name’

name = gets

name = name.chomp

puts ‘Hello ‘ + name

Here, ‘chomp’ is a string method, which will omit all the trailing characters after the space.

Class and syntax in Ruby

Class is like a blueprint that combines both characteristics and functions. Individual objects can be formed from a class.

Here is an example.

In case of a cuboid, its height, length, and breadth can be considered to be members of the class Cuboid.

class Test

def welcome

puts “Welcome Fellow Coders to Ruby Programming!”

end

end

# Now using above class to create objects

obj = Test.new

obj.welcome

This is an example of a simple class ‘Test’. obj is an instance/object of the class Test. On the instance/object, calling the method welcome welcomes you to Ruby classes and objects. Let us look at the method in detail, in the next class.

Global variables: Variables that can be added anywhere, throughout a program, are called global variables.

  • A global variable starts with the special character – dollar sign ($). For example: $radius, $counter, $name and $5.
  • Remember, until declared, the value of a global variable will always be ‘nil’.

What follows is an example of how a global variable is used:

$glob

puts #$glob

Output:nil

$global = 10

class C

puts “in a class: #{$global}”

end

puts “at top-level, $global: #{$global}”

Output

• in a class: 10

• at top-level, $global: 10

Class variables: Variables within a single class structure are called class variables.

  • Class variables begin with @@. Example: @@total = 0
  • It is necessary to initialise class variables before they can be used in method definitions.
  • An error will appear if an uninitialised class variable is referenced.
  • Class variables are shared between all instances of a class.

Instance variables: Instance variables help to define the characteristics or attributes of objects.

  • Instance variables begin with ‘@’– a special character. For example: @ins_var.
  • They cannot be accessed directly from the class definitions, but only within definite objects across varied methods within a class instance.
  • Until declared, the value of an instance variable will always remain ‘nil’.

In this example, Employee.new creates a new object — an instance of the class Employee. The instance variable is @emp_id.

class Employee

def initialize(emp_id, emp_name)

@emp_id = emp_id

@emp_name = emp_name

end

def display

puts “Employee ID and Name: “

puts @emp_id, @emp_name

end

end

Employee.new(23434, “Anand”).display

Employee.new(343434, “Ram”).display

Output:

Employee ID and Name:

23434

Anand

Employee ID and Name:

343434

Ram

Local variables: Local variables have a name beginning with an underscore (_) or a lower case letter (from a-z). Local variables have scope inside the following:

  • class … end
  • module … end
  • def … end
  • From a block’s opening brace to its close brace. Example: {}: proc{ … }, loop{ … }
  • The whole program (except when any one of the above applies)

Shown below is an example of a local variable:

name = “Anand”

def method1

name = “Anand”

puts “Name within method1: “,name

end

def method2

name = “Ram”

puts “Name within method2: “,name

end

method1

method2

method1

puts “Name outside methods: “+name

Output

Name inside method1

Anand

Name inside method2:

Ram

Name inside method1:

Anand

Name outside methods: Anand

Looping in Ruby

In Ruby, loops help in the execution of the same code block, a number of times. The while loop, one of the most used in programming languages, helps in executing a code block when a given condition is true.

The syntax is:

while condition [do]

code

end

…or:

code while condition

…or:

begin

code

end while condition

An example is:

$j = 0

$num = 10

while $j < $num do

puts “Inside loop j = #$j”

$j +=1

end

The until statement: Unlike the while statement, the until statement helps in the execution of a block of code when the condition is false.

The syntax is:

until conditional [do]

code

end

…or:

code until conditional

…or:

begin

code

end until conditional

An example is:

$j = 0

$num = 5

until $j > $num do

puts “Inside the loop j = #$j”

$j +=1;

end

The for loop: A for statement in Ruby is used for the execution code, once for each of the elements in an expression.

The syntax is:

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

code

end

For example:

for a in 0..5

puts “Value of variable is #{a}”

end

The break statement: A break statement helps in the termination of an internal loop. Here is an example:

for a in 0..5

if a > 2 then

break

end

puts “Value of the variable is #{a}”

end

Output

Value of the variable is 0

Value of the variable is 1

Value of the variable is 2

The next statement: A next statement helps in jumping to the next iteration of the most internal loop. For example:

for a in 0..5

if a < 2 then

next

end

puts “Value is #{a}”

end

Output

Value is 2

Value is 3

Value is 4

Value is 5

The redo statement: The redo statement in Ruby helps in restarting the iteration of the most internal loop. It helps to restart yield or call if called within a block, without checking the loop condition. For example:

for a in 0..5

if a < 2 then

puts “Value is #{a}”

redo

end

end

Output

Value is 0

Value is 0

............

This will be an infinite loop.

Arrays

Arrays are like bags that contain things. They comprise groups of objects, of any data type, arranged in a sequence. Arrays are zero based since the index of the first item is always zero.

.each do is a an iterator method which returns all the elements of an array.

Ways of creating arrays: There are several ways to create arrays in Ruby.

numerals = [14,15, 16, 17, 18]

fruits = %w( mango grape melon )

bills = Array.new

bills << 4.55 << 3.22 << 3.55 << 8.55 << 3.23

all_datatype = [1, -5,”text”, 4.3]

puts numerals.inspect

puts fruits.inspect

puts bills.inspect

puts all_datatype.inspect

In the above example ‘%w’ will allow you to add elements in an array without a comma, while ‘inspect’ allows you to view the array object.

Hash

A hash comprises pairs of information, where each pair contains a name or a unique key and a value. Hashes are sometimes called associated arrays. In contrast to arrays, hashes may have arbitrary objects like indexes. There are two ways to create hashes — new keyword and hash literal.

Here’s an example of creating a hash using a new keyword:

animals = Hash.new

#adding two pairs of values to the hash

animals[1] = "Dog"

animals[2] = "Cat"

animals[3]= "Rabbit"

puts animals

#Output : {1=>"Dog", 2=>"Cat", 3=>"Rabbit"}

Note: Instead of the square brackets [ ] you can also use the store method for initialising the hash with certain values.

Blocks

Blocks are unidentified pieces of code that accept arguments and return a value. They are useful in passing a piece of code as an argument to a method using proc, which will be discussed later.

Also, they can be associated with an array to perform various operations.

For syntax in the blocks, use the following commands:

Single statement: ‘curly braces’

Multiple statements: ‘do and end’”

Example: The following code gives you an idea of what a block looks like. Blocks should be associated with an array or method to actually work.

#multiple statements

do

puts “I am Ruby”

puts “greeting you from inside a block!”

end

#Single statement

{ puts “I am Ruby, greeting you from inside a block!” }

Exception handling

  • In Ruby, exceptional conditions represent an object, which can either be a descendant or an instance of the exception class.
  • An exception can be handled by providing a rescue clause, whereby the program control will flow to this clause.
  • The predefined classes in Ruby, like exception and its children, are used to handle program errors.
  • Some of the built-in Ruby sub-classes of exceptions are: NoMemoryError, ScriptError, SecurityError, SignalException, StandardError, SystemExit, SystemStackError and fatal error.

LEAVE A REPLY

Please enter your comment!
Please enter your name here