Professional Documents
Culture Documents
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.
# Examples of symbols
:name
:a_symbol
:"surprisingly, this is also a symbol"
Ruby Basic
4. Numbers
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'.
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:
− Subtraction − Subtracts right hand operand from left hand a - b will give -10
Ruby Arithmetic Operators operand.
a = 10 , b = 20
/ 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.
== 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 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.
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
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)
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
what is an arrays ?
what is an arrays ?
Another way to do the above would be with the shovel operator (<<).
uniq: This iterates through an array, deletes any duplicate values that exist, then returns the result as a new array.
select:
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.
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.
#
Ruby Basic
VI. Hashes
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.
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
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.
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.
Syntax
module Identifier
statement1
statement2
...........
end
Ruby Basic
X. modules
#!/usr/bin/ruby
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