Wednesday, April 7, 2021

RUBY TUTORIAL

RubyIcon

1. Introduction to Ruby:

Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives an understanding of Ruby.

This tutorial has been prepared for beginners to help them understand the basic concepts related to Ruby Scripting languages.

1.1 Define Keywords:

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.

1.2 Install Ruby:

install: to install ruby go to : https://www.ruby-lang.org/en/downloads/

Click here to Download Ruby

1.3 Ruby Editor:

Ruby Editor: for editing ruby codes, you can use every text editor knows like: sublime text, Atom, VSC, etc. Or you can use the interactive Ruby (IRb) which provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line.

$irb
irb 0.6.1(99/09/16)
irb(main):001:0> puts “hello world”
#Result
$ hello world

2. Ruby Basic:

2.1 Hello world:

Hello World: 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.

puts "Hello Word!"
print "Hello Word!"

Here, we assumed that you have a 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 Word!
$ Hello Word!

2.2 getting user input:

Getting user input: gets method help to interact with the computer in order to type an input

Example of gets method :

puts “what is your name?”
 name = gets
 puts “your name is” + name
 Result
 $ what is your name?
 $ Root Lindow
 $ your name is Root Lindow

2.3 Comments:

Single line comment: A single line comment starts with the # character and they extend from # to the end of the line

#This is a comment
 puts "Hello Word!"
 #Result
 $ Hello Word!Word!

Multi-line comments: You can comment on multiple lines using =begin and =end syntax

=begin
 This is a
 multi-line comment
 =end
 puts "Hello Word!"
 #Result
 $ Hello Word!

3. Operators:

Ruby supports several operators, and most operators are actually method calls.

For each operator (+ – * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator (+= -= etc.).

3.1 Arithmetic Operators:

Arithmetic Operators

3.2 Comparison Operators:

Comparison Operators

3.3 Assignment Operators:

Assignment Operators

3.4 Logical Operators:

Logical Operators

4. Data Types:

4.1 Strings:

There are five types of variables supported by Ruby:

Strings :

  • A string is a text
  • Wrap text in a pair of quotation marks:

‘Single quotes are fine’
“So are double quotes”

Example of a string as a variable

 name = “Root”
 surname = “Lindow”
 puts name
 puts surname

 #can use the + sign for concatenation
 puts name + “ ” + surname
 
 #can use the = sign for assignment
 name, surname = surname, name
 puts name
 puts surname
 
 #can use the == sign to compare two string
 puts name == surname
 
 #can find string
 puts name.length

 #can use the * sign to multiply a string
 puts name * 3
 
 #find the element or print in a range of a string
 puts surname[1]
 puts surname[2, 3]
 puts surname[2..3]
 
 #Result
 $ Root
 $ Lindow
 $ Lindow Root
 $ Lindow
 $ Root
 $ false
 $ 4
 $ RootRootRoot
 $ i
 $ ndo
 $ nd

4.2 Numbers:

  • Integers – numbers without decimal points(e.g., 5, -2)
  • Floats – numbers with decimal points (e.g., 3.14, -0.123)

Example of numbers as a variable

 grade1 = 70
 grade12 = 7.5
 
 #can use the arithmetic operators for calculations
 total1 = grade1 + grade12
 total2 = grade1 – grade12
 total3 = grade1 / grade12
 total4 = grade1 * grade12
 total5 = grade1 % grade12
 puts grade1
 puts grade
 puts total1
 puts total2
 puts total3
 puts total4
 puts total5
 
 #use the gets method
 puts “put the first number”
 n1 = gets.to_i #convert the input into a integer
 puts “put the second number”
 n2 = gets.to_i #convert the input into a integer
 sum = n1 + n2
 puts “the sum is : #{sum}”
 
 #Result
 $ 70
 $ 7.5
 $ 77.5
 $ 62.5
 $ 10.3333333333
 $ 525
 $ 4.75
 $ put the first number
 $ 10
 $ put the second number
 $ 20
 $ the sum is : 30

4.3 Collection:

  • An array is also called List, it’s a collection of value and we can also obtain a specific data using the Index

Example of Collection as an Array:

fruits = [‘orange’, ‘apple’, ‘kiwi’, 1, 15]

puts fruits
puts fruits[1] #using the index
puts fruits.length #find the length
fruits.delete(‘apple’) #delete a element in the array
puts fruits.length #find the length after deleting on element

Fruits1 = [‘lemon’, 10]

puts fruits.merge(fruits1) #merge two arrays

#Result
$ [‘orange’, ‘apple’, ‘kiwi’, 1, 15]
$ [‘apple’]
$ 5
$ 4
$ [‘orange’, ‘kiwi’, 1, 15, ‘lemon’, 10]
  • Hashes are also called Dictionary, map or associative array

Example of Collection as Hash:

identity = {‘name’ => ‘Root’, ‘surname’ => ‘Lindow’, ‘age’ => 23}

puts identity
puts identity[‘name’] #using the key
puts identity.keys #find keys
puts identity.length #find the length
identity.delete(‘age’) #delete a element in the array
puts identity.has_key?(‘age’) #find if the key exist

identity1 = {‘city’ => ‘Paris’}
puts identity.merge(identity1) #merge two hashes

#Result
$ {‘name’ => ‘Root’, ‘surname’ => ‘Lindow’, ‘age’ => 23}
$ ‘Root’
$ [‘name’, ‘surname’, ‘age’]
$ 3
$ false
$ {‘name’ => ‘Root’, ‘surname’ => ‘Lindow’, ‘city’ => ‘Paris’}

4.4 Boolean:

Boolean: true and false some codes can be evaluated to true or false for many comparison methods.

  • Numeric comparison:

Example of a Numeric comparison:

1 < 2
2 >= 5
1 == 1
58.0 != 58.7

#Result
$ true
$ false
$ true
$ false
  • String Equality:

Example of a String Equality:

“yellow” == “oranges”
“yellow” != “oranges”

#Result
$ false
$ true

4.5 Date and Time:

Class Time represents the date and time in Ruby. It is a separate process through which the system’s date and time are assigned by the function. This class cannot represent files before 1970 or after 2038 in your system.

  • Current Date and time:

Example of current Date and time:

time1 = Time.new
time2 = Time.now

puts “The current time and date : ” + time1.inspect
puts “The current time and date : ” + time2.inspect

#Result
$ The current time and date : Wed Dec 04 12:02:39 -0700 2019
$ The current time and date : Wed Dec 04 12:02:39 -0700 2019
  • Components of date and time:

Example of components of date and time:

time1 = Time.new
puts “The current time and date : ” + time1.inspect
puts time.year # Year of the date
puts time.month # Month of the date (1 to 12)
puts time.day # Day of the date (1 to 31 )
puts time.wday # 0: Day of week: 0 is Sunday
puts time.yday # 365: Day of year
puts time.hour # 23: 24-hour clock
puts time.min # 59
puts time.sec # 59
puts time.usec # 999999: microseconds
puts time.zone # "UTC": timezone name

#Result
$ The current time and date : Wed Dec 04 12:04:39 -0700 2019

$ 2019
$ 12
$ 4
$ 3
$ 337
$ 12
$ 4
$ 39
$ 1577234222328
$ UTC

4.6 Range:

ranges as sequences have a start point, an endpoint, and a way to produce successive values in the sequence.

Ruby creates these sequences 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.

(1..6) # 1,2,3,4,5,6
(1...6) # 1,2,3,4,5
(‘a’..’e’) # ‘a’, ‘b’, ‘c’, ‘d’, ‘e’

Example of Ranges:

$, = “, ” # the separator for values in a array
range1 = (1..5).to_a # to_a put the values of the variable in array
range2 = (‘car’..’cat’).to_a

print “{#range1}”
print “{#range2}”

#Result
$ [1, 2, 3, 4, 5]
$ [“car”, “cas”, “cat”]

You can iterate ranges methods by testing their contents.

Examples:

range1 = 1..5
puts range1.include?(3) # find if the number 3 is include in the range

rg = range1.min
print “{“the min value is : ”#rg}” # find the minimum number

rg = range1.max
print “{“the max value is : ”#rg}” # find the maximum number

#Result
$ true
$ the min value is : 0
$ the max value is : 5

5. Conditions:

Ruby offers conditional structures that are pretty common to modern languages. Here, we will explain all the conditional statements.

5.1 if…else Statement:

Syntax:

if conditional
   code
elsif conditional
   code
else
  code

If expressions are used for conditional execution. The values false and nil are false, and everything else is true. Notice Ruby uses elsif, not else if nor elif.

Executes code if the conditional is true. If the conditional is not true, the code specified in the else clause is executed.

And if expression’s conditional is separated from code by the reserved word then, a new line, or a semicolon

Example of If..else condition

x = 2
if x > 3
  puts “x is greater than 2”
elsif x == 2 and x != 0
     puts “x is perfect”
else
  puts “ha find it yourself”

#Result
$ x is perfect

5.2 unless Statement:

5.3 case Statement: