You are on page 1of 57

Ruby Basic

Ruby Basic

1. Overview

Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan.
Ruby Basic
Overview
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 Basic
1. Literal

A literal is any notation that lets you represent a fixed value in source code.

'Hello, world!' // string literal


375 // integer literal
3.141528 // float literal
true // boolean literal
{ 'a' => 1, 'b' => 2 } // hash literal
[ 1, 2, 3 ] // array literal
:sym // symbol literal
nil
Ruby Basic
2. Strings

A string is a list of characters in a specific sequence. In programming

# Ex. 1: with double quotes


"The man said, 'Hi there!'"

# Ex 2: with single quotes and escaping


'The man said, \'Hi there!\''
The backslash, or escape (\) character, tells the computer that the
Ruby Basic
2. Strings

Double quotes allow something called string interpolation

irb :001 > a = 'ten'


=> "ten"

irb :002 > "My favorite number is #{a}!"


=> "My favorite number is ten!"
Ruby Basic
3. Symbols

Ruby symbols are created by placing a colon (:) before a word.

# Examples of symbols
:name
:a_symbol
:"surprisingly, this is also a symbol"
Ruby Basic
4. Numbers

Numbers are represented many ways in Ruby.

# Example of integer literals


1, 2, 3, 50, 10, 4345098098

# Example of float literals


1.2345, 2345.4267, 98.2234
Ruby Basic
5. nil

In programming, we need a way to express "nothing", and in Ruby, we do this through something called nil.
A variable with a value of nil could be described as having 'nothing' or being 'completely empty', or even just simply
'not any specific type'.

irb :001 > puts "Hello, World!"


Hello, World!
=> nil
Ruby Basic
5. nil

The puts method prints out a string and returns nothing, so we see nil being returned after the string is displayed.
###
You can explicitly refer to the nil value by using the nil literal in our code:

irb :002 > x = nil # nil literal used here


=> nil
Ruby Basic
Operator Description Example
6. Operations
+ Addition − Adds values on either side of the operator. a + b will give 30

− Subtraction − Subtracts right hand operand from left hand a - b will give -10
Ruby Arithmetic Operators operand.
a = 10 , b = 20

* Multiplication − Multiplies values on either side of the a * b will give 200


operator.

/ Division − Divides left hand operand by right hand operand. b / a will give 2

% Modulus − Divides left hand operand by right hand operand b % a will give 0
and returns remainder.

** Exponent − Performs exponential (power) calculation on a**b will give 10 to the


operators. power 20
Ruby Basic Operator Description Example

== Checks if the value of two operands are equal or not, if yes (a == b) is not true.
6. Operations then condition becomes true.

!= Checks if the value of two operands are equal or not, if (a != b) is true.


Ruby Comparison values are not equal then condition becomes true.
Operators
a= 10 , b = 20
> Checks if the value of left operand is greater than the value (a > b) is not true.
of right operand, if yes then condition becomes true.

< Checks if the value of left operand is less than the value of (a < b) is true.
right operand, if yes then condition becomes true.

>= Checks if the value of left operand is greater than or equal (a >= b) is not true.
to the value of right operand, if yes then condition becomes
true.

<= Checks if the value of left operand is less than or equal to (a <= b) is true.
the value of right operand, if yes then condition becomes
true.
Ruby Basic Operator Description Example

<=> Combined comparison operator. Returns 0 if first operand (a <=> b) returns -1.
6. Operations equals second, 1 if first operand is greater than the second
and -1 if first operand is less than the second.

=== Used to test equality within a when clause of a case (1...10) === 5 returns
Ruby Comparison
statement. true.
Operators
a= 10 , b = 20 .eql? True if the receiver and argument have both the same type 1 == 1.0 returns true,
and equal values. but 1.eql?(1.0) is false.

equal? if aObj is duplicate of


bObj then aObj ==
True if the receiver and argument have the same object id. bObj is true, a.equal?
bObj is false but
a.equal?aObj is true.
Operator Description Example

Ruby Basic and Called Logical AND operator. If both the operands are true, then the
condition becomes true.
(a and b)
is true.

6. Operations or Called Logical OR Operator. If any of the two operands are non zero, then (a or b) is
the condition becomes true. true.

&& Called Logical AND operator. If both the operands are non zero, then the (a && b)
condition becomes true. is true.

|| Called Logical OR Operator. If any of the two operands are non zero, then (a || b) is
Ruby Logical Operators the condition becomes true. true.

a=10 , b = 20
! Called Logical NOT Operator. Use to reverses the logical state of its !(a && b)
operand. If a condition is true, then Logical NOT operator will make false. is false.

not Called Logical NOT Operator. Use to reverses the logical state of its not(a &&
operand. If a condition is true, then Logical NOT operator will make false. b) is
false.
Ruby Basic
6. Operations

Operator Description Example


Ruby Ternary Operator
?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y
Ruby Basic
6. Operations
Operator Description Example

Ruby Range Operators .. Creates a range from start point to end point 1..10 Creates a range from 1 to 10
inclusive. inclusive.

... Creates a range from start point to end point 1...10 Creates a range from 1 to 9.
exclusive.
Ruby Basic
II. Variables
Starting Type
character
Document:
https://viblo.asia/p/variables-s $ Biến global (global variable)
cope-trong-ruby-bWrZnBkmZx
@ Biến instance (instance variable)
w
[a-z] or _ Biến local (local variable)

[A-Z] Biến constant (constant variable)

@@ Biến class (class variable)


Ruby Basic
III. Ruby - if...else, case, unless

1. if...else
x=1
if x > 2
if conditional [then] puts "x is greater than 2"
code... elsif x <= 2 and x!=0
[elsif conditional [then] puts "x is 1"
code...]... else
[else puts "I can't guess the number"
code...] end
end => X is 1
Ruby Basic
III. Ruby - if...else, case, unless

2. Case
$age = 5
case $age
case expr0 when 0 .. 2
when expr1, expr2 puts "baby"
when 3 .. 6
stmt1 puts "little child"
when expr3, expr4 when 7 .. 12
puts "child"
stmt2 when 13 .. 18
else puts "youth"
else
stmt3 puts "adult"
end end
=> little child
Ruby Basic
III. Ruby - if...else, case, unless

3. unless
x = 1
unless x>=2
unless conditional [then] puts "x is less than
code 2"
else
[else puts "x is greater
code ] than 2"
end
end
=> x is less than 2
Ruby Basic
IV. Loop

1. while $i = 0
$num = 5
while conditional [do] while $i < $num do
code puts("Inside the loop
i = #$i" )
end $i +=1
end

=>
Inside the loop i = 0
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Ruby Basic
IV. Loop

1. while modifier $i = 0
$num = 5
code while condition begin
puts("Inside the loop
i = #$i" )
OR $i +=1
end while $i < $num
begin
code =>
Inside the loop i = 0
end while conditional
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Ruby Basic
IV. Loop

2. until $i = 0
$num = 5
until conditional [do]
code
until $i > $num do
end puts("Inside the loop
i = #$i" )
$i +=1;
end

=>
Inside the loop i = 0
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Inside the loop i = 5
Ruby Basic
IV. Loop

2. until modifier $i = 0
$num = 5
code until conditional begin
puts("Inside the loop
i = #$i" )
OR $i +=1;
end until $i > $num
begin
code =>
Inside the loop i = 0
end until conditional
Inside the loop i = 1
Inside the loop i = 2
Inside the loop i = 3
Inside the loop i = 4
Inside the loop i = 5
Ruby Basic
IV. Loop

3. for for i in 0..5


puts "Value of local
for variable [, variable ...] in expression [do] variable is #{i}"
end
code
end
Ruby Basic
IV. Loop

4. iterator names = ['Bob', 'Joe', 'Steve', 'Janice', 'Susan', 'Helen']


x=1
collection.each do |variable|
code
names.each do |name|
end puts "#{x}. #{name}"
x += 1
end
Ruby Basic
V. Arrays

what is an arrays ?

An array is an ordered list of elements that can be of any type.

array = [1, 'Bob', 4.33, 'another string']


Ruby Basic
V. Arrays

what is an arrays ?

An array is an ordered list of elements that can be of any type.

array = [1, 'Bob', 4.33, 'another string']


irb :003 > array.first
=> 1
irb :004 > array.last
=> "another string"
Ruby Basic
V. Arrays
Modifying Arrays
irb :007 > array.pop
=> "another string"
irb :008 > array
=> [1, "Bob", 4.33]

irb :009 > array.push("another string")


=> [1, "Bob", 4.33, "another string"]

Another way to do the above would be with the shovel operator (<<).

irb :010 > array.pop


=> "another string"
irb :011 > array << "another string"
=> [1, "Bob", 4.33, "another string"]
Ruby Basic
V. Arrays
Modifying Arrays
The map method iterates over an array applying a block to each element of the array and returns a new array with those results.

irb :001 > a = [1, 2, 3, 4]


=> [1, 2, 3, 4]
irb :002 > a.map { |num| num**2 }
=> [1, 4, 9, 16]
irb :003 > a.collect { |num| num**2 }
=> [1, 4, 9, 16]
irb :004 > a
=> [1, 2, 3, 4]
Ruby Basic
V. Arrays
Modifying Arrays
The delete_at method can be helpful if you'd like to eliminate the value at a certain index from your array

irb :005 > a.delete_at(1)


=> 2
irb :006 > a
=> [1, 3, 4]
Ruby Basic
V. Arrays
Modifying Arrays
As a side note, sometimes you will know the value that you want to delete, but not the index.

irb :007 > my_pets = ["cat", "dog", "bird", "cat", "snake"]


=> ["cat", "dog", "bird", "cat", "snake"]
irb :008 > my_pets.delete("cat")
=> "cat"
irb :009 > my_pets
=> ["dog", "bird", "snake"]
Ruby Basic
V. Arrays
Modifying Arrays

uniq: This iterates through an array, deletes any duplicate values that exist, then returns the result as a new array.

irb :010 > b = [1, 1, 2, 2, 3, 3, 4, 4]


=> [1, 1, 2, 2, 3, 3, 4, 4]
irb :011 > b.uniq
=> [1, 2, 3, 4]
irb :012 > b
=> [1, 1, 2, 2, 3, 3, 4, 4]
Ruby Basic
V. Arrays
Iteration Over an Array

select:

irb :001 > numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb :002 > numbers.select { |number| number > 4 }
=> [5, 6, 7, 8, 9, 10]
irb :003 > numbers
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Ruby Basic
V. Arrays
Common Array Methods

This section will introduce you to some common methods that Ruby has built-in to its Array class.

include?
irb :001 > a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb :002 > a.include?(3)
=> true
irb :003 > a.include?(6)
=> false
Ruby Basic
V. Arrays
Common Array Methods

This section will introduce you to some common methods that Ruby has built-in to its Array class.

flatten
The flatten method can be used to take an array that contains nested arrays and create a one-dimensional array.

irb: 001 > a = [1, 2, [3, 4, 5], [6, 7]]


=> [1, 2, [3, 4, 5], [6, 7]]
irb: 002 > a.flatten
=> [1, 2, 3, 4, 5, 6, 7]
Ruby Basic
V. Arrays
Common Array Methods

This section will introduce you to some common methods that Ruby has built-in to its Array class.

each_index
The each_index method iterates through the array much like the each method, however the variable represents the index
number as opposed to the value at each index
irb: 001 > a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb: 002 > a.each_index { |i| puts "This is index #{i}" }
Ruby Basic
VI. Hashes

Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.

irb :001 > old_syntax_hash = {:name => 'bob'}


=> {:name=>'bob'}
The newer syntax is introduced in Ruby version 1.9 and is much simpler. As you can see, the result is the same.

irb :002 > new_hash = {name: 'bob'}


=> {:name=>'bob'}
Ruby Basic
VI. Hashes

you wanted to add on to an existing hash.


irb :004 > person[:hair] = 'brown'
=> "brown"
irb :005 > person
=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown'}

irb :006> person[:age] = 62


=> 62
irb :007> person
=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown', :age=>62}
And what if you want to remove something from an existing hash?

irb :008 > person.delete(:age)


=> 62
irb :009 > person
=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown'}

#
Ruby Basic
VI. Hashes

merge two hashes together:

irb :011 > person.merge!(new_hash)


=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown', :name=>'bob'}
Ruby Basic
VII. Blocks

Ruby has a concept of Block.

A block consists of chunks of code.

You assign a name to a block.

The code in the block is always enclosed within braces ({}).

A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the
name test, then you use the function test to invoke this block.

You invoke a block by using the yield stateme


Ruby Basic
VII. Blocks
def test
puts "You are in the method"
yield
puts "You are again back to the method"
yield
end
test {puts "You are in the block"}
=>
You are in the method
You are in the block
You are again back to the method
You are in the block
Ruby Basic
VIII. methods

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to
bundle one or more repeatable statements into a single unit.

def say
#method body goes here
end
def say(words)
puts words
end

say("hello")
say("hi")
Ruby Basic
VIII. methods

types methods:
- methods without arguments
- methods with arguments
- argument’s default value
- variadic arguments
Ruby Basic
VIII. methods

types methods:
methods without arguments : A method can be defined and invoked without argument.

def method_without_arg()
"without arg"
end

irb> method_without_arg
=> "without arg"
irb> method_without_arg()
=> "without arg"
Ruby Basic
VIII. methods

types methods:
methods with arguments : On the other hand, a method can also be defined and invoked with arguments
def method_with_args arg1
"with args: #{arg1}"
end

irb> method_with_args 'an argument'


=> "with args: an argument"
irb> method_with_args('an argument')
=> "with args: an argument"
Ruby Basic
VIII. methods

types methods:
arguments’ default values: You can supply a default value for an argument. In this case, if a value for the
argument isn’t supplied, then the default value will be used instead
def method_with_default_value(newsletter = 'ruby.devscoop.fr')
"The Ruby newsletter is #{newsletter}"
end
irb> method_with_default_value 'awesome'
=> "The Ruby newsletter is awesome"
irb> method_with_default_value
=> "The Ruby newsletter is ruby.devscoop.fr"
Ruby Basic
VIII. methods

types methods:
variadic arguments: Ruby methods can support a variable-length argument lists
def method_with_varargs *names
puts names.class, "\n"
names.each {|name| puts name}
end
irb> method_with_varargs 'Mehdi', 'John', 'Sam'
Array
Mehdi
John
Sam
Ruby Basic
VIII. methods

keyword arguments: are an alternative to positional arguments. They’re pretty similar to passing a hash to a
method, but with more explicit errors.

def method_with_keyword_arguments(foo: 'bar')


"foo is #{foo}"
end

irb> method_with_keyword_arguments foo: 'naughty'


=> "foo is naughty"
irb> method_with_keyword_arguments
=> "foo is bar"
Ruby Basic
VIII. methods

block as argument: The ampersand parameter & allows you to automatically store the content of a block in an
instance of Proc which is assigned to the ampersand parameter
def method_with_block &blk
p blk.class
blk.call
end
irb> method_with_block { puts 'a block' }
Proc
a block
=> nil
Ruby Basic
IX. class and object
Defining a class in Ruby:
Syntax:

class Class_name

end
Ruby Basic
IX. class and object
#defining class Vehicle
class Vehicle
#initialize method
def initialize(id, color, name)
#variables
@veh_id = id
@veh_color = color
@veh_name = name
#displaying values
puts "ID is: #@veh_id"
puts "Color is: #@veh_color"
puts "Name is: #@veh_name"
puts "\n"
end
end
Ruby Basic
IX. class and object
Creating Objects using the “new” method in Ruby:
we can create a number of objects from a single class. In Ruby, objects are created by the new method.

Syntax:
object_name = Class_name.new
eg:
xveh = Vehicle. new("1", "Red", "ABC")
yveh = Vehicle. new("2", "Black", "XYZ")
Output:

ID is: 1
Color is: Red
Name is: ABC

ID is: 2
Color is: Black
Name is: XYZ
Ruby Basic
X. modules
Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.

Modules provide a namespace and prevent name clashes.

Modules implement the mixin facility.

Syntax
module Identifier
statement1
statement2
...........
end
Ruby Basic
X. modules
#!/usr/bin/ruby

# Module defined in trig.rb file

module Trig
PI = 3.141592654
def Trig.sin(x)
# ..
end
def Trig.cos(x)
# ..
end
end
Ruby Basic
X. modules
Mixins : Ruby does not support multiple inheritance directly but Ruby Modules have another wonderful use.
At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.

Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the
code in the mixin starts to interact with code in the class that uses it.
Ruby Basic
X. modules
Mixins :
module A
def a1
end
def a2
end
end
module B
def b1
end
def b2
end
end

class Sample
include A
include B
def s1
end
end

samp = Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1

You might also like