Skip to main content

Ruby on Rails Part 1 - Introduction to Ruby

 

Ruby on rails Part 1 - Introduction to Ruby

 

Table of content 

  1. Introduction
  2. Installation
  3. Basics IRB
    1. Printing to console
    2. Comments
  4. Variables
  5. Data types
  6. Chomp
  7. User input
  8. Data structure
    1. Arrays
    2. Hash
    3. Set
  9. Branching
  10. Loops
  11. Methods
  12. Class and objects

Introduction

Ruby programming language is a pure object oriented programming language. Ruby is a scripting language designed by Yukihiro Matsumoto (Matz). It was designed in 1993.  Just like Smalltalk, Ruby is a perfect object-oriented language. with much easier syntax than Smalltalk.
 
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 has a clean and easy syntax that allows a new developer to learn very quickly and easily.
  • Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.

Installation 

  1. For Ubuntu/Linux

                To install ruby using apt, run the command in terminal :

                                             $ sudo apt-get install ruby-full

                To check the path of the ruby installation : 

                                             $ which ruby

                To check the version of the ruby installed :

                                             $ ruby  --version

      2. For Windows

                Download ruby installer from here . Run it and follow the instructions.

      3. For MacOS: we can use brew to install ruby 

                                             $ brew install ruby

Basics IRB 

Ruby has an interactive ruby shell called irb. Type irb in the terminal and it opens the shell.


Print to console

Comments

Comments in Ruby start with # symbol.

                        # This is a single line comment

                        = This is a multi line

                        comment =

Variables

Primitive Data Types 

  1. Integer: Denotes an integer 

  2. Float: Denotes fractional numbers 

  3. String: Denotes a sequnce of characters 

  4. Boolean: Denotes true or false value 

  5. Symbols: Similar to strings, start with a : and are immutable. Example - :someThing, :123 

  6. Array: Collection of similar objects 

  7. Hashes: Key-Value pair

Chomp  

This method removes record separators (/r, /n, etc) or the specified sub-string from the end of the string. 

            str = ‘string\r\n’
            puts str.chomp # Prints string without /r and /n
            puts str.chomp(‘ng’) # Prints stri

Get user input 

We have a gets that reads data from the console. The type of the data is string.

            varName = gets
            # Gets user input as string and stores it in varName

            varName1 = gets.chomp.to_i
            # Gets user input as string then converts it to int and then stores it in varName1

Data structure

Array

Array is an indexed sequential data structure. He is an heterogeneous data structure.

            arr = [1,2,3] # Creates array with 3 elements
            arr = Array.new(10) # Creates empty array of size 10
            arr.push(4) or arr<<(4) # Adds element to the end
            arr.unshift(5) # Adds element to the start
            arr.insert(index, element) # Adds element at the specified index
            arr[index] # Returns element at index

Hash (Dictionary/key-value pair) 

Hash data structure is a key-value pair data structure. There are three ways to declare a Hash. We can access the values by using the key in the hash. 

hash1 = { “Key1” => “Value1”, # defining Hash
“Key2” => “Value2”,
“Key3” => “Value3”
}

hash2 = Hash.new #Another way of defining Hash

hash3 = Hash.new(“Default Value”)
#This default value is returned for all keys whose values aren’t defined yet

hash3[5] #This will return Default Value
hash3[9] #This will return Default Value
puts hash1[“Key2”] # Prints Value2
hash1[“Key4”] = “Value4” # Add new key value pair

Set

Set is data structure that hold unique values. It internally implements a Hash data structure. It hold only unique values.

set1 = Set.new #Creates an empty set
set2 = Set[1,2] #Creates new set with 2 elements
set3 = [1,2,3,4].to_set #Converts an array to set
set1.add(1) #Add new element to the set
set2.merge([2,3,4]) #Merges an array with the set
set2.delete(2) #Deletes 2 from set2

If-Else

if 1 > 2
puts “No!”
elif 0 > 1
puts “Noo!”
else
puts “Yes”
end

Switch case

arr = [1,2,3,4]
case arr
when 1
puts 1
when 2
puts 2
when 3
puts 3
else
puts "else"
end

Loops            

for varName in 0..5 # For each item in range 0 to 5
puts varName # print 0 1 2 3 4 5
end


for varName in [1,2,3,4] # For each item in range 1 to 4
puts varName # print 1 2 3 4
end

 

while condition == true do # While some condition is true
puts “Inside loop# Execute this statement
end


loop do # This is a do-while loop
puts “Hello” # Execute the loop first
if condition == false # Then check for the condition
break # Break out of the loop if false
end
end

until and unless

i = 1
until i == 10
puts i
i += 1
end

 

x =3
unless x < 5 # Opposite of if. Executes when condition is false
puts "Inside unless" # Similar to “if not” or “if !”
else
puts "Inside unless-else"
end

Methods

Methods are code blocks in Ruby. They can be parameterized and return multiple values.

def methodName(parameterName) # Creates a method with 1 parameter
puts "Hello #{parameterName}" # Prints the parameter name
return "Done Printing" # Returns “Done Printing”
end

def methodName(Everyone) # Calling the method and passing a string



def method1(val1 = "default1") # Default parameter example
puts default1
end 

 

def method2 # Can skip () after methodName. Even with arg
i = 1
j = 2
k = 3
return i, j, k # Can return multiple values
end

They can take variable number of arguments.

def method3 *args # Accepts multiple and stores it in array
for i in 0..args.length
puts i
end
end

Classes and Objects

class ClassName
@name = '' #This is an instance variable
def initialize(name)
@name = name
end

def getName()
puts "Name is #{@name}"
end
end

obj = ClassName.new("Everyone")
obj.getName() 

A variable starting with @ is an instance variable. That means its value is specific to an object whereas a variable starting with @@ is a class variable (Static variable). The value of such variable is accessible to all instances of the class.

Important Functions

objectName.methods.sort # Returns all available methods for this object (Sorted)
objectName.class # Specifies the type of object
objectName.object_id # Returns memory address of the object

break and next 

break => This keyword is used to break out of a loop/condition statement

next   => This is similar to continue in other languages. Used to skip the current iteration

retry and redo 

redo is used to repeat the current iteration of the loop 

retry is used to restart the execution of the block from the start (1st iteration). Can only be used in exception handling.

for i in 0..5 # Loop should print 0 to 5
puts i # Prints till 3
redo if i==3 # Now the loop gets stuck at value i == 3. Hence an infinite loop
end

The ruby code is save in a file with .rb extension. To run a ruby program, type ruby fileName.rb from the terminal.

Thank you folks. If you like my post, do check my other posts here.

Most viewed

Ruby on rails part 6 - Blocks , lambda, procs and closure

 Blocks , lambda, procs  and closure Table of content  1. Blocks 2. Lambda 3. Procs 4. Closure Blocks  Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or between brackets {} 
. Blocks can have multiple arguments
. The argument names are defined between two pipe | characters. Blocks are typically used with ‘each’ method which iterates over a list. Syntax of block using {} ['List of items'].each { | block arguments|  block body }  Syntax of block using do-end ['List of items'].each do | block arguments |      # block body end Example of block declared as do-end with each method.   [ 1 , 2 , 3 ].each do |num| puts num end     Output   $ ruby block_with_each.rb 1 2 3 $    Blocks can also be saved in variables or passed as argument to another function.   yield is a Ruby keyword that is used to call a block. When you use the yield keyword, the code inside the block will run. Example of saving a bl