You are on page 1of 46

Ruby

langage avec un syntaxe lgante qui est


naturel lire et facile crire.

Tout est un objet


>> "amine".capitalize
=> "Amine"
>> 7.next
=> 8
>> false.class
=> FalseClass
>> [1, 80, 9].sort
=> [1, 9, 80]

Les Nombres
> 100.class
=> Fixnum
> 10000000000000000000.class
=> Bignum
> 100.0.class
=> Float

Les Nombres
> 1 + 2
=> 3
> 1 + 2.0
=> 3.0
> 1.0 + 2
=> 3.0
> 1 / 2
=> 0
> 1.0 / 2
=> 0.5

String
> "Seconds/day: #{24 * 60 * 60}"
=> Seconds/day: 86400
> 'Seconds/day: #{24 * 60 * 60}'
=> Seconds/day: #{24 * 60 * 60}
> "Code #{'Yo ' * 3}!!!1"
=> Code Yo Yo Yo !!!1
> 'Am' + "ine"
=> "Amine"

String
str = "Programming. Do you speak it?"
=> "Programming. Do you speak it?"
str[13]
=> "D"
str.slice(13)
=> "D"
str[13, 12]
=> "Do you speak"
str.slice(13, 12)
=> "Do you speak"
str[13..-5]
=> "Do you speak"

Practice
chocolate_name = "Milka"
chocolate_rating = 4
chocolate_details = "good product"
Result :
Milka is a very very very very good chocolate
-----

chocolate_name = "Galaxy"
chocolate_rating = 1
chocolate_details = "awesome product"
Result :
Milka is a very awesome chocolate

Array
> [[1, 2, 3], 10, 3.14, "This is a string", pow(2)]
=> [[1, 2, 3], 10, 3.14, "This is a string", 4]
> languages = 'Ruby', 'JavaScript', 'Python', 'PHP'
=> ["Ruby", "JavaScript", "Python", "PHP"]
> languages[0]
=> "Ruby"
> languages.at(0)
=> "Ruby"
> languages[4]
=> nil
> languages[1] = "CoffeeScript"
=> "CoffeeScript"
> languages
=> ["Ruby", "CoffeeScript", "Python", "PHP"]

Array
> languages.push("Closure")
=> ["Ruby", "JavaScript", "Python", "PHP", "Closure"]
> languages << "Haskell"
=> ["Ruby", "JavaScript", "Python", "PHP", "Closure", "Haskell"]
> languages.unshift("C++")
=> ["C++", "Ruby", "JavaScript", "Python", "PHP", "Closure", "Haskell"]
> languages.insert(3, "CoffeeScript")
=> ["C++", "Ruby", "JavaScript", "CoffeeScript", "Python", "PHP", "Closure", "Haskell"]
> languages.insert(4, "Haml", "Sass")
=> ["C++", "Ruby", "JavaScript", "CoffeeScript", "Haml", "Sass", "Python", "PHP", "Closure",
"Haskell"]

Array
> languages.pop
=> "Haskell"
> languages
=> ["C++", "Ruby", "JavaScript", "CoffeeScript", "Haml", "Sass", "Python", "PHP", "Closure"]
> languages.delete("PHP")
=> "PHP"
> languages
=> ["Ruby", "JavaScript", "Haml", "Sass", "Python", "Closure"]

> languages = "Ruby", "JavaScript", "PHP", "Python", "PHP"


> languages.uniq
=> ["Ruby", "JavaScript", "PHP", "Python"]

Array
> languages = "Ruby", "JavaScript", "PHP", "Python", "PHP"
=> ["Ruby", "JavaScript", "PHP", "Python", "PHP"]
> languages.length
> languages.count
> languages.size
=> 5
> languages.empty?
=> false
> languages.include?('Ruby')
=> true
> languages.include?('Closure')
=> false

Array
> os = ["Fedora", "SUSE", "Red Hat", "MacOS", "Windows"]
> linux_os = ["SUSE", "Red Hat", "Ubuntu", "Fedora"]
> os | linux_os
=> ["Fedora", "SUSE", "Red Hat", "MacOS", "Windows", "Ubuntu"]
> os & linux_os
=> ["Fedora", "SUSE", "Red Hat"]
> os - linux_os
=> ["MacOS", "Windows"]
> linux_os - os
=> ["Ubuntu"]
> linux_os + ["Debian", "Gentoo"]
=> ["SUSE", "Red Hat", "Ubuntu", "Fedora", "Debian", "Gentoo"]
> linux_os * 2
=> ["SUSE", "Red Hat", "Ubuntu", "Fedora", "SUSE", "Red Hat", "Ubuntu", "Fedora"]
> linux_os * ", "
=> "SUSE, Red Hat, Ubuntu, Fedora"

Array
a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }
a -- b -- c -a.each_index {|x| print x, " -- " }
0 -- 1 -- 2 -a.each_with_index {|item, index| puts "[#{index}] => #{item}" }
[0] => a
[1] => b
[2] => c

Practice
chocolates = ["Milka","Galaxy"]
Result :
There is 2 types of chocolates :
1- Milka
2- Galaxy

Hash
> {:font_size => 10, :font_family => "Arial"}
=> {:font_size=>10, :font_family=>"Arial"}
> {font_size: 10, font_family: "Arial"}
=> {:font_size=>10, :font_family=>"Arial"}
> Hash.new
=> {}
> :ruby.object_id
=> 319048
> :ruby.object_id
=> 319048
> "ruby".object_id
=> 70200985531220
> "ruby".object_id
=> 70200985514360

Hash
h = { "a" => 100, "b" => 200 }
h.each {|key, value| puts "#{key} is #{value}" }
a is 100
b is 200
=> {"a"=>100, "b"=>200}
h.key?("a")
=> true
h.value?(100)
=> true
h.keys
=> ["a", "b"]
h.values
=> [100, 200]

Practice
chocolates = [{:name => "Milka", :rate => 4, :details => "good product"},
{:name => "Galaxy", :rate => 1, :details => "awesome product"}]
Result :
There is 2 types of chocolates :
1- Milka is very very very very good chocolate!
2- Galaxy is awesome good chocolate!

Time
t = Time.new
=> 2014-09-24 14:50:25 +0300
t.year
=> 2014
t.month
=> 9
t.day
=> 24
t.day.next
=> 25

Vars
v = "Ruby"
=> "Ruby"
defined? v
=> "local-variable"
@i = "Ruby"
=> "Ruby"
defined? @i
=> "instance-variable"
$g = "Ruby"
=> "Ruby"
defined? $g
=> "global-variable"
C = "Ruby"
=> "Ruby"
defined? C
=> "constant"

Condition
if 1==1
print "true-"
end
print "true-" if 1==1
if 1!=2
print "true"
end
unless 1==2
print "true"
end
print "true-" unless 1==2

Condition
a = 1
res = if a < 5
"#{a} less than 5"
elsif a > 5
"#{a} greater than 5"
else
"#{a} equals 5"
end
res
=> "1 less than 5"

Practice
chocolate = {:name => "Milka", :rate => 4, :limit_time => "2014-10-05"}
Result :
Milka is very good chocolate!
----------------------------------

chocolate = {:name => "Galaxy", :rate => 1, :limit_time => "2014-08-03"}


Result :
Eghh! Galaxy is so bad!
----------------------------------

chocolate = {:name => "Galaxy", :rate => 1, :limit_time => "2014-10-03"}


Result :
Galaxy is normal chocolate!

Loop
i = 1
while i < 11
print "#{i} "
i += 1
end
#=> 1 2 3 4 6 7 8 9 10
i = 11
begin
print "#{i} "
i += 1
end while i < 10
#=> 11

Loop
i = 1
until i > 10
print "#{i} "
i += 1
end
#=> 1 2 3 4 6 7 8 9 10
for i in 1..10
print "#{i} "
end
#=> 1 2 3 4 6 7 8 9 10
[1,2,3,4,5,6,7,8,9,10].each {|value| print "#{value} "}
#=> 1 2 3 4 6 7 8 9 10
10.times {|i| print "#{i} "}
#=> 0 1 2 3 4 6 7 8 9

Methods
def movie_listing(title, rank = 5)
"#{title.capitalize} has a rank of #{rank}"
end
movie_listing("goonies", 10)
=> "Goonies has a rank of 10"
movie_listing("ghostbusters", 9)
=> "Ghostbusters has a rank of 9"
movie_listing("goldfinger")
=> "Goldfinger has a rank of 5"

Methods
def split_apart(first, *split, last)
"first: #{first.inspect}, split: #{split.inspect}, last: #{last.inspect}"
end
split_apart(1, 2)
=> "first: 1, split: [], last: 2"
split_apart(1, 2, 3)
=> "first: 1, split: [2], last: 3"
split_apart(1, 2, 3, 4)
=> "first: 1, split: [2, 3], last: 4"

Methods
def meth_two(arg)
if arg > 0
"positive"
elsif arg < 0
"negative"
else
"zero"
end
end
meth_two(23)
=> "positive"
meth_two(0)
=> "zero"

Methods
def double(p1)
yield(p1*2)
end
double(3) { |val| "I got #{val}" }
=> "I got 6"
double("tom") do |val|
"Then I got #{val}"
end
=> "Then I got tomtom"

Methods
def thrice
yield
yield
yield
end
x = 5
puts "value of x before: #{x}"
=> "value of x before: 5"
thrice { x += 1 }
puts "value of x after: #{x}"
=> "value of x after: 8"

Methods
movie = ""
movie.empty?
=> true
movie = "Goonies"
movie.empty?
=> false
movie.include?("G")
=> true
movie.include?("x")
=> false

Methods
movie = "Ghostbusters"
=> "Ghostbusters"
movie.reverse
=> "sretsubtsohG"
movie
=> "Ghostbusters"
movie.reverse!
=> "sretsubtsohG"
movie
=> "sretsubtsohG"

Practice
Coder ces mthodes :
1- Trier les chocolats en ordre alphabtique des nom ( croissant ou dcroissant c
est paramtre )
2- Trier en ordre des rate
3- Enlevez les chocolats prim
4- Chercher un chocolat et le retourner ( en nom )
5- Chercher les chocolats avec un rate prcie.

Class
class BookInStock
def initialize(title, author, price)
@title = title
@author = author
@price = Float(price)
end
end
BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99)

Class
class BookInStock
def initialize(title, author, price)
@title = title
@author = author
@price = Float(price)
end
def to_s
"Book: #{@title} / #{@author}, #{@price}"
end
end
book = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99)
book.to_s # => Book: The Great Gatsby / F. Scott Fitzgerald, 8.99

Class
class BookInStock
def initialize(title, price)
@title = title
@price = Float(price)
end
def title
@title
end
def title=(value)
@title = value
end
end
book = BookInStock.new("The Great Gatsby", 8.99)
book.title # => The Great Gatsby
book.title = "This Side of Paradise"
book.title # => This Side of Paradise
book.price
# => NoMethodError: undefined method `price'
book.price = 10 # => NoMethodError: undefined method `price='

Class
class BookInStock
def initialize(title, author, price)
@title, @author, @price = title, author, Float(price)
end
def price_in_cents
Integer(@price * 100 + 0.5)
end
def price_in_cents=(value)
@price = value / 100.0
end
end
book = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99)
book.price_in_cents = 100
book.price
# => 1.0
book.price_in_cents
# => 100

Class
class BookInStock
def initialize(title, author, price)
@title = title
@author = author
@price = Float(price)
end
def +(other)
BookInStock.new("#{@title}, #{other.title}", "#{@author} and #{other.author}", @price+other.
price)
end
end
fitzgerald_book = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99)
hemingway_book = BookInStock.new("The Old Man and the Sea ", "Ernest Hemingway", 7.6)
books_collection = fitzgerald_book + hemingway_book
books_collection.title # => The Great Gatsby, The Old Man and the Sea
books_collection.author # => F. Scott Fitzgerald and Ernest Hemingway
books_collection.price # => 16.59

Class
book1 = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99) # => BookInStock:
0x00000000e71cb0
book2 = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99) # => BookInStock:
0x00000000e553f8
book1 == book2 # => false

Class
book1 = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99) # => BookInStock:
0x00000000e71cb0
book2 = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99) # => BookInStock:
0x00000000e553f8
book1 == book2 # => false

def ==(other)
if other.is_a? BookInStock
@title == other.title && @author == other.author && @price == other.price
else
false
end
end

Class
class BookInStock
def initialize(title, author, price)
@title, @author, @price = title, author, Float(price)
end
def self.total_amount(*books)
books.map(&:price).inject(0, &:+)
end
end
book1 = BookInStock.new("t1", "a1", 10)
book2 = BookInStock.new("t2", "a2", 20)
BookInStock.total_amount(book1, book2) # => 30.0

Class
class BookInStock
@@count = 0
def initialize(title, author, price)
@title, @author, @price = title, author, Float(price)
@@count += 1
end
def self.statistics
"Count of books: " + @@count.to_s
end
end
5.times{ BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99) }
BookInStock.statistics # => Count of books: 5
book = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99)
book.count # => NoMethodError: undefined method 'count'

Class
class BookInStock
@count = 0
def initialize(title, author, price)
@title, @author, @price = title, author, Float(price)
end
def self.add
@count += 1
end
def self.statistics
"Count of add method call: " + @count.to_s
end
end
BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99)
5.times{ BookInStock.add }
BookInStock.statistics # => Count of add method call: 5

Class
class BookInStock
PUBLISHING = "Book House"
end
BookInStock::PUBLISHING # => Books House

Class
class PrintPublication
def initialize(title, author)
@title, @author = title, author
end
end
class BookInStock < PrintPublication
def initialize(title, author, price)
@price = price
super(title, author)
end
end
book = BookInStock.new("The Great Gatsby", "F. Scott Fitzgerald", 8.99)
# => #<BookInStock:0x000000024f2408 @price=8.99, @title="The Great Gatsby", @author="F. Scott
Fitzgerald">

Class
class A
@@value = 1
def self.value
@@value
end
end
A.value # => 1
class B < A
@@value = 2
end
class C < A
@@value = 3
end
B.value # => 3

Class
class A
NUM = 2
end
class B < A
end
A::NUM # => 2
B::NUM # => 2

You might also like