Programmeren met Ruby
       The Ruby Way 1
Ruby installeren



Windows: http://rubyinstaller.org/

Linux en OSX: http://www.ruby-lang.org
Ruby scripts runnen
IRB - Interactive Ruby
.rb files


> ruby mijn_script.rb
van PHP naar Ruby
van PHP naar Ruby
   (overeenkomsten)
Geen variabelen declareren

Er zijn classes met public, protected en private toegang

String interpolatie php: “$foo is een $bar” ruby: “#{foo} is een #{bar}”

Er zijn Exceptions

true en false hebben dezelfde behaviour als in php
van PHP naar Ruby
      (verschillen)
Ruby kent strong typing: je moet to_s, to_i, etc ... gebruiken bij
conversies

strings, nummers, arrays, hashes zijn objecten abs(-1) wordt -1.abs

gebruik van () is optioneel bij functies

variabelen zijn referenties

Er zijn geen abstracte Classes

Hashes en Arrays zijn niet omwisselbaar met elkaar

Alleen false en nil zijn false: 0, array(), “” zijn true
Duck Typing
Duck typing

“Als een Object loopt als een eend
en het geluid maakt van een eend,
dan beschouwen we het als een eend.”
Duck typing

def append_song(result, song)
 unless result.kind_of?(String)
  fail TypeError.new("String expected")
 end

 unless song.kind_of?(Song)
  fail TypeError.new("Song expected")
 end

 result << song.title << " (" << song.artist << ")"
end
result = ""
append_song(result, song)
Duck typing

                                                      def append_song(result, song)
def append_song(result, song)
                                                       result << song.title << " (" << song.artist << ")"
 unless result.kind_of?(String)
                                                      end
  fail TypeError.new("String expected")
 end
                                                      result = ""
 unless song.kind_of?(Song)                           append_song(result, song)
  fail TypeError.new("Song expected")
 end

 result << song.title << " (" << song.artist << ")"
end
result = ""
append_song(result, song)
Objecten
Objecten
class BookInStock
 def initialize(isbn, price)
  @isbn = isbn
  @price = Float(price)
 end
end

b1 = BookInStock.new("isbn1", 3)
p b1
=> #<BookInStock:0x0000010086aeb0 @isbn="isbn1", @price=3.0>

b2 = BookInStock.new("isbn2", 3.14)
p b2
=> #<BookInStock:0x0000010086ad48 @isbn="isbn2", @price=3.14>

b3 = BookInStock.new("isbn3", "5.67")
p b3
=> #<BookInStock:0x0000010086ac58 @isbn="isbn3", @price=5.67>
Objecten
class BookInStock
 def initialize(isbn, price)
  @isbn = isbn
  @price = Float(price)
 end
end

b1 = BookInStock.new("isbn1", 3)
puts b1
=> #<BookInStock:0x0000010086aeb0>

b2 = BookInStock.new("isbn2", 3.14)
puts b2
=> #<BookInStock:0x0000010086ad48>

b3 = BookInStock.new("isbn3", "5.67")
puts b3
=> #<BookInStock:0x0000010086ac58>
Objecten
class BookInStock
 def initialize(isbn, price)
  @isbn = isbn
  @price = Float(price)
 end
 def to_s
  "ISBN: #{@isbn}, price: #{@price}"
 end
end

b1 = BookInStock.new("isbn1", 3)
puts b1
=> ISBN: isbn1, price: 3.0

b2 = BookInStock.new("isbn2", 3.14)
puts b2
=> ISBN: isbn2, price: 3.14

b3 = BookInStock.new("isbn3", "5.67")
puts b3
=> ISBN: isbn3, price: 5.67
Objecten
class BookInStock
 def initialize(isbn, price)
  @isbn = isbn
  @price = Float(price)                 instance variabelen
 end
 def to_s
  "ISBN: #{@isbn}, price: #{@price}"
 end
end

b1 = BookInStock.new("isbn1", 3)
puts b1
=> ISBN: isbn1, price: 3.0

b2 = BookInStock.new("isbn2", 3.14)
puts b2
=> ISBN: isbn2, price: 3.14

b3 = BookInStock.new("isbn3", "5.67")
puts b3
=> ISBN: isbn3, price: 5.67
Instance variabelen
Instance variabelen



instance variabelen zijn private

Alleen het object zelf kan ze manipuleren
Attributen
Attributen
Getters
Attributen
 Getters
class BookInStock
 def initialize(isbn, price)
  @isbn = isbn
  @price = Float(price)
 end
 def isbn
  @isbn
 end
 def price
  @price
 end
 # ..
end
Attributen
 Getters                       Setters
class BookInStock
 def initialize(isbn, price)
  @isbn = isbn
  @price = Float(price)
 end
 def isbn
  @isbn
 end
 def price
  @price
 end
 # ..
end
Attributen
 Getters                        Setters
class BookInStock              class BookInStock
 def initialize(isbn, price)    def initialize(isbn, price)
  @isbn = isbn                   @isbn = isbn
  @price = Float(price)          @price = Float(price)
 end                            end
 def isbn                       def price=(new_price)
  @isbn                          @price = new_price
 end                            end
 def price
  @price                        # ..
 end                           end
 # ..
end
The Ruby Way
  class BookInStock
   attr_reader      :isbn
   attr_accessor :price
   def initialize(isbn, price)
    @isbn = isbn
    @price = Float(price)
   end
  # ...
  end
The Ruby Way
  class BookInStock
   attr_reader      :isbn
   attr_accessor :price
   def initialize(isbn, price)
    @isbn = isbn
    @price = Float(price)
   end
  # ...
  end

  book = BookInStock.new("isbn1", 33.80)
  puts "ISBN = #{book.isbn}"
  => ISBN = isbn1
The Ruby Way
  class BookInStock
   attr_reader      :isbn
   attr_accessor :price
   def initialize(isbn, price)
    @isbn = isbn
    @price = Float(price)
   end
  # ...
  end

  book = BookInStock.new("isbn1", 33.80)
  puts "ISBN = #{book.isbn}"
  => ISBN = isbn1

  puts "Price = #{book.price}"
  => Price = 33.8
The Ruby Way
  class BookInStock
   attr_reader      :isbn
   attr_accessor :price
   def initialize(isbn, price)
    @isbn = isbn
    @price = Float(price)
   end
  # ...
  end

  book = BookInStock.new("isbn1", 33.80)
  puts "ISBN = #{book.isbn}"
  => ISBN = isbn1

  puts "Price = #{book.price}"
  => Price = 33.8

  book.price = book.price * 0.75
  puts "New price = #{book.price}"
  => New price = 25.349999999999998
Arrays & Hashes
Arrays
Een collectie van objecten, geïndexeerd door een
                 positieve integer
Arrays
Een collectie van objecten, geïndexeerd door een
                 positieve integer
       a = [ 3.14159, "pie", 99 ]       b = Array.new
       a.class                          b.class
       => Array                         => Array

       a.length                         b.length
       => 3                             => 0

       a[0]                             b[0] = "second"
       => 3.14159                       b[1] = "array"

       a[1]                             b
       => "pie"                         => ["second", "array"]

       a[2]
       => 99

       a[3]
       => nil
Arrays
  Stacks                          FIFO
stack = []                    queue = []
stack.push "red"              queue.push "red"
stack.push "green"            queue.push "green"
stack.push "blue"
p stack                       puts queue.shift
=> ["red", "green", "blue"]   => red
                              puts queue.shift
puts stack.pop                => green
=> blue
puts stack.pop
=> green
puts stack.pop
=> red
p stack
=> []
Hashes
Een collectie van objecten, dat geïndexeerd kan
          worden door elk objecttype
Hashes
Een collectie van objecten, dat geïndexeerd kan
          worden door elk objecttype

           h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
Hashes
Een collectie van objecten, dat geïndexeerd kan
          worden door elk objecttype

           h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }


           h = { :dog => 'canine', :cat => 'feline', :donkey => 'asinine' }
Hashes
Een collectie van objecten, dat geïndexeerd kan
          worden door elk objecttype

           h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }


           h = { :dog => 'canine', :cat => 'feline', :donkey => 'asinine' }
Symbolen


Unieke constanten zonder waarden

Eerste karakter “:” gevolgd door een naam

Voornamelijk gebruikt als keys voor Hash

{:name => “Ruby”} of {name: “Ruby”}
Blocks en Iterators
Blocks en Iterators
top_five = {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1}
Blocks en Iterators
top_five = {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1}

for i in 0...5
  word = top_five[i][0]
  count = top_five[i][1]
  puts "#{word}: #{count}"
end
Blocks en Iterators
top_five = {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1}

for i in 0...5
  word = top_five[i][0]
  count = top_five[i][1]
  puts "#{word}: #{count}"
end

top_five.each do |word, count|
  puts "#{word}: #{count}"
end
Blocks en Iterators
top_five = {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1}

for i in 0...5
  word = top_five[i][0]
  count = top_five[i][1]
  puts "#{word}: #{count}"
end

top_five.each do |word, count|
  puts "#{word}: #{count}"                Block
end
Blocks en Iterators
top_five = {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1}

for i in 0...5
  word = top_five[i][0]
  count = top_five[i][1]
  puts "#{word}: #{count}"
end

top_five.each do |word, count|           Iterator
  puts "#{word}: #{count}"               Block
end
Blocks

Een stuk code tussen {} of do end keywords

Kan parameters meekrijgen tussen | param1 |

Parameters zijn altijd gescoped binnen het
block

Variabelen zijn gescoped binnen een block,
behalve als ze buiten het block gedefinieerd
staan
Blocks
sum = 0
[1, 2, 3, 4].each do |value|
  square = value * value
  sum += square
end

puts sum
=> 30
Blocks
sum = 0                        square = Shape.new(sides: 4)
[1, 2, 3, 4].each do |value|   #
  square = value * value       # .. een heleboel code
  sum += square                #
end
                               sum = 0
puts sum                       [1, 2, 3, 4].each do |value|
=> 30                            square = value * value
                                 sum += square
                               end

                               puts sum
                               square.draw    # BOOM!
Blocks
sum = 0                        square = Shape.new(sides: 4)
[1, 2, 3, 4].each do |value|   #
  square = value * value       # .. een heleboel code
  sum += square                #
end
                               sum = 0
puts sum                       [1, 2, 3, 4].each do |value; square|
=> 30                            square = value * value
                                 sum += square
                               end

                               puts sum
                               square.draw
Inheritance, Modules &
        Mixins
Inheritance
class Parent
end
class Child < Parent
end

puts "The superclass of Child is #{Child.superclass}"
=> “The superclass of Child is Parent”

puts "The superclass of Parent is #{Parent.superclass}"
=> “The superclass of Parent is Object”

puts "The superclass of Object is #{Object.superclass}"
=> “The superclass of Object is BasicObject”

puts "The superclass of BasicObject is #{BasicObject.superclass.inspect}"
=> “The superclass of BasicObject is nil”
Modules


Groep van methods, classes en constanten

Eigen namespace

Kunnen gebruikt worden voor Mixins
Modules
module Trig
 PI = 3.141592654
 def Trig.sin(x)
  puts x
 end
end

module Moral
 VERY_BAD = 0
 BAD = 1
 def Moral.sin(badness)
   puts badness
 end
end
Modules
module Trig
 PI = 3.141592654
 def Trig.sin(x)
  puts x
 end
end

module Moral
 VERY_BAD = 0
 BAD = 1
 def Moral.sin(badness)
   puts badness
 end
end

y = Trig.sin(Trig::PI/4)
wrongdoing = Moral.sin(Moral::VERY_BAD)

=> 0.7853981635
=> 0
Modules
module Trig
 PI = 3.141592654
 def Trig.sin(x)
  puts x
 end                                      Module methods
end

module Moral
 VERY_BAD = 0
 BAD = 1
 def Moral.sin(badness)
   puts badness
 end
end

y = Trig.sin(Trig::PI/4)
wrongdoing = Moral.sin(Moral::VERY_BAD)

=> 0.7853981635
=> 0
Instance methods?
Instance methods?
 module Debug
  def who_am_i?
    "#{self.class.name} (id: #{self.object_id}): #{self.name}"
  end
 end
Instance methods?
  module Debug
   def who_am_i?
     "#{self.class.name} (id: #{self.object_id}): #{self.name}"
   end
  end




FOUT: Een module is geen Class
Wat heb je er dan aan?
Mixins
module Debug
 def who_am_i?
   "#{self.class.name} (id: #{self.object_id}): #{self.name}"
 end
end
Mixins
module Debug
 def who_am_i?
   "#{self.class.name} (id: #{self.object_id}): #{self.name}"
 end
end

   class Phonograph              class EightTrack
     include Debug                 include Debug
     attr_reader :name             attr_reader :name
     def initialize(name)          def initialize(name)
       @name = name                  @name = name
     end                           end
     # ...                         # ...
   end                           end
Mixins
module Debug
 def who_am_i?
   "#{self.class.name} (id: #{self.object_id}): #{self.name}"
 end
end

   class Phonograph              class EightTrack
     include Debug                 include Debug
     attr_reader :name             attr_reader :name
     def initialize(name)          def initialize(name)
       @name = name                  @name = name
     end                           end
     # ...                         # ...
   end                           end
Mixins
module Debug
 def who_am_i?
   "#{self.class.name} (id: #{self.object_id}): #{self.name}"
 end
end

   class Phonograph              class EightTrack
     include Debug                 include Debug
     attr_reader :name             attr_reader :name
     def initialize(name)          def initialize(name)
       @name = name                  @name = name
     end                           end
     # ...                         # ...
   end                           end

         ph = Phonograph.new("West End Blues")
         et = EightTrack.new("Surrealistic Pillow")

         ph.who_am_i?
         et.who_am_i?
Mixins
module Debug
 def who_am_i?
   "#{self.class.name} (id: #{self.object_id}): #{self.name}"
 end
end

   class Phonograph              class EightTrack
     include Debug                 include Debug
     attr_reader :name             attr_reader :name
     def initialize(name)          def initialize(name)
       @name = name                  @name = name
     end                           end
     # ...                         # ...
   end                           end

         ph = Phonograph.new("West End Blues")
         et = EightTrack.new("Surrealistic Pillow")

         ph.who_am_i? # => "Phonograph (id: 2151894340): West End Blues"
         et.who_am_i? # => "EightTrack (id: 2151894300): Surrealistic Pillow"
Include
include is alleen een referentie naar de
module

Als de module in een ander bestand staat
dan is require nodig om de module
beschikbaar te maken

LET OP: Als een method wijzigt in de module
dan wijzigt deze voor alle classes die de
module includen
Methods & Arguments
Methods
Worden definieerd met def

Beginnen met een kleine letter of een
underscore (_)

Kunnen eindigen met een letter of cijfer

Kunnen eindigen met een ? (boolean)

Kunnen eindigen met een = (setters)

Kunnen eindigen met een ! (bang methods)
Arguments
def my_new_method(arg1, arg2, arg3)
 # ...
end
Arguments
def my_new_method(arg1, arg2, arg3)
 # ...
end


def my_other_new_method
 # ...
end
Arguments
def my_new_method(arg1, arg2, arg3)
 # ...
end


def my_other_new_method
 # ...
end


def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach")
 "#{arg1}, #{arg2}, #{arg3}."
end
Arguments
def my_new_method(arg1, arg2, arg3)
 # ...
end


def my_other_new_method
 # ...
end


def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach")
 "#{arg1}, #{arg2}, #{arg3}."
end


def varargs(arg1, *rest)
 "arg1=#{arg1}. rest=#{rest.inspect}"
end
Expressions
Expresions


Alles dat redelijkerwijs een waarde kan
terug geven doet dat ook

Bijna alles is een expression
Expresions

[ 3, 1, 7, 0 ].sort.reverse # => [7, 3, 1, 0]
Expresions
[ 3, 1, 7, 0 ].sort.reverse # => [7, 3, 1, 0]


song_type = if song.mp3_type == MP3::Jazz
   if song.written < Date.new(1935, 1, 1)
     Song::TradJazz
   else
     Song::Jazz
   end
  else
    Song::Other
  end


rating = case votes_cast
         when 0...10 then Rating::SkipThisOne
         when 10...50 then Rating::CouldDoBetter
         else Rating::Rave
         end
Vergelijken van objecten

==          Test dezelfde waarde.
===         Vergelijk of een element binnen een bepaald berijk valt. (1..10) === 5
<=>         Algemene vergelijkingsoperator. Geeft -1 bij kleiner dan, 0 bij gelijk, of +1 bij groter dan
<,<=,>=,>   Vergelijking voor kleiner dan, kleiner en gelijk, groter dan, groter en gelijk.
=~           Reguliere expressie vergelijking
eql?        True als de elementen dezelfde waarde en type hebben 1.eql?(1.0) is false.
equal?      True als de elementen dezelfde objectID hebben
Conditioneel uitvoeren
nil && 99     # => nil
false && 99   # => false
"cat" && 99   # => 99
Conditioneel uitvoeren
nil && 99     # => nil
false && 99   # => false
"cat" && 99   # => 99


nil || 99   # => 99
false || 99 # => 99
"cat" || 99 # => "cat"
Conditioneel uitvoeren
nil && 99     # => nil     var ||= "default value"
false && 99   # => false
"cat" && 99   # => 99


nil || 99   # => 99
false || 99 # => 99
"cat" || 99 # => "cat"
Conditioneel uitvoeren
nil && 99     # => nil     var ||= "default value"
false && 99   # => false
"cat" && 99   # => 99


nil || 99   # => 99        month, day, year = $1, $2, $3 if date =~ /(dd)-(dd)-(dd)/
false || 99 # => 99        puts "a = #{a}" if DEBUG
"cat" || 99 # => "cat"     print total unless total.zero?
Conditioneel uitvoeren
nil && 99     # => nil             var ||= "default value"
false && 99   # => false
"cat" && 99   # => 99


nil || 99   # => 99                month, day, year = $1, $2, $3 if date =~ /(dd)-(dd)-(dd)/
false || 99 # => 99                puts "a = #{a}" if $DEBUG
"cat" || 99 # => "cat"             print total unless total.zero?


               cost = duration > 180 ? 0.35 : 0.25
Terug naar loops
Loops?
while line = gets
 # ...
end
Loops?
                        until play_list.duration > 60
while line = gets
                         play_list.add(song_list.pop)
 # ...
                        end
end
Iterators
3.times do
  print "Ho! "
end
=> Ho! Ho! Ho!
Iterators
3.times do
  print "Ho! "
end
=> Ho! Ho! Ho!


0.step(12, 3) {|x| print x, " " }
=> 0 3 6 9 12
Iterators
3.times do
  print "Ho! "
end
=> Ho! Ho! Ho!


0.step(12, 3) {|x| print x, " " }
=> 0 3 6 9 12


File.open("ordinal").grep(/d$/) do |line|
  puts line
end
Iterators
3.times do                                  0.upto(9) do |x|
  print "Ho! "                                print x, " "
end                                         end
=> Ho! Ho! Ho!                              => 0 1 2 3 4 5 6 7 8 9


0.step(12, 3) {|x| print x, " " }
=> 0 3 6 9 12


File.open("ordinal").grep(/d$/) do |line|
  puts line
end
Iterators
3.times do                                  0.upto(9) do |x|
  print "Ho! "                                print x, " "
end                                         end
=> Ho! Ho! Ho!                              => 0 1 2 3 4 5 6 7 8 9


0.step(12, 3) {|x| print x, " " }           [ 1, 1, 2, 3, 5 ].each {|val| print val, " " }
=> 0 3 6 9 12                               => 1 1 2 3 5


File.open("ordinal").grep(/d$/) do |line|
  puts line
end
Iterators
3.times do                                  0.upto(9) do |x|
  print "Ho! "                                print x, " "
end                                         end
=> Ho! Ho! Ho!                              => 0 1 2 3 4 5 6 7 8 9


0.step(12, 3) {|x| print x, " " }           [ 1, 1, 2, 3, 5 ].each {|val| print val, " " }
=> 0 3 6 9 12                               => 1 1 2 3 5


File.open("ordinal").grep(/d$/) do |line|   playlist.each do |song|
  puts line                                   song.play
end                                         end
Exceptions
Exceptions
require 'open-uri'
page = "podcasts"
file_name = "#{page}.html"
web_page = open("http:/  /pragprog.com/#{page}")
output = File.open(file_name, "w")
while line = web_page.gets
  output.puts line
end
output.close
Exceptions
require 'open-uri'
page = "podcasts"
file_name = "#{page}.html"
web_page = open("http:/  /pragprog.com/#{page}")
output = File.open(file_name, "w")
begin
  while line = web_page.gets
    output.puts line
  end
  output.close
rescue Exception
  STDERR.puts "Failed to download #{page}: #{$!}"
  output.close
  File.delete(file_name)
  raise
end
En nu?
En nu?
http://tryruby.org/levels/1/challenges/0
Opdrachten

Verhaalgenerator

Crazy 8-Ball Spel

Steen, papier, schaar

Blackjack Spel

Boter, Kaas en Eieren Spel

1 the ruby way

  • 1.
    Programmeren met Ruby The Ruby Way 1
  • 2.
  • 3.
  • 4.
  • 5.
    .rb files > rubymijn_script.rb
  • 6.
  • 7.
    van PHP naarRuby (overeenkomsten) Geen variabelen declareren Er zijn classes met public, protected en private toegang String interpolatie php: “$foo is een $bar” ruby: “#{foo} is een #{bar}” Er zijn Exceptions true en false hebben dezelfde behaviour als in php
  • 8.
    van PHP naarRuby (verschillen) Ruby kent strong typing: je moet to_s, to_i, etc ... gebruiken bij conversies strings, nummers, arrays, hashes zijn objecten abs(-1) wordt -1.abs gebruik van () is optioneel bij functies variabelen zijn referenties Er zijn geen abstracte Classes Hashes en Arrays zijn niet omwisselbaar met elkaar Alleen false en nil zijn false: 0, array(), “” zijn true
  • 9.
  • 10.
    Duck typing “Als eenObject loopt als een eend en het geluid maakt van een eend, dan beschouwen we het als een eend.”
  • 11.
    Duck typing def append_song(result,song) unless result.kind_of?(String) fail TypeError.new("String expected") end unless song.kind_of?(Song) fail TypeError.new("Song expected") end result << song.title << " (" << song.artist << ")" end result = "" append_song(result, song)
  • 12.
    Duck typing def append_song(result, song) def append_song(result, song) result << song.title << " (" << song.artist << ")" unless result.kind_of?(String) end fail TypeError.new("String expected") end result = "" unless song.kind_of?(Song) append_song(result, song) fail TypeError.new("Song expected") end result << song.title << " (" << song.artist << ")" end result = "" append_song(result, song)
  • 13.
  • 14.
    Objecten class BookInStock definitialize(isbn, price) @isbn = isbn @price = Float(price) end end b1 = BookInStock.new("isbn1", 3) p b1 => #<BookInStock:0x0000010086aeb0 @isbn="isbn1", @price=3.0> b2 = BookInStock.new("isbn2", 3.14) p b2 => #<BookInStock:0x0000010086ad48 @isbn="isbn2", @price=3.14> b3 = BookInStock.new("isbn3", "5.67") p b3 => #<BookInStock:0x0000010086ac58 @isbn="isbn3", @price=5.67>
  • 15.
    Objecten class BookInStock definitialize(isbn, price) @isbn = isbn @price = Float(price) end end b1 = BookInStock.new("isbn1", 3) puts b1 => #<BookInStock:0x0000010086aeb0> b2 = BookInStock.new("isbn2", 3.14) puts b2 => #<BookInStock:0x0000010086ad48> b3 = BookInStock.new("isbn3", "5.67") puts b3 => #<BookInStock:0x0000010086ac58>
  • 16.
    Objecten class BookInStock definitialize(isbn, price) @isbn = isbn @price = Float(price) end def to_s "ISBN: #{@isbn}, price: #{@price}" end end b1 = BookInStock.new("isbn1", 3) puts b1 => ISBN: isbn1, price: 3.0 b2 = BookInStock.new("isbn2", 3.14) puts b2 => ISBN: isbn2, price: 3.14 b3 = BookInStock.new("isbn3", "5.67") puts b3 => ISBN: isbn3, price: 5.67
  • 17.
    Objecten class BookInStock definitialize(isbn, price) @isbn = isbn @price = Float(price) instance variabelen end def to_s "ISBN: #{@isbn}, price: #{@price}" end end b1 = BookInStock.new("isbn1", 3) puts b1 => ISBN: isbn1, price: 3.0 b2 = BookInStock.new("isbn2", 3.14) puts b2 => ISBN: isbn2, price: 3.14 b3 = BookInStock.new("isbn3", "5.67") puts b3 => ISBN: isbn3, price: 5.67
  • 18.
  • 19.
    Instance variabelen instance variabelenzijn private Alleen het object zelf kan ze manipuleren
  • 20.
  • 21.
  • 22.
    Attributen Getters class BookInStock def initialize(isbn, price) @isbn = isbn @price = Float(price) end def isbn @isbn end def price @price end # .. end
  • 23.
    Attributen Getters Setters class BookInStock def initialize(isbn, price) @isbn = isbn @price = Float(price) end def isbn @isbn end def price @price end # .. end
  • 24.
    Attributen Getters Setters class BookInStock class BookInStock def initialize(isbn, price) def initialize(isbn, price) @isbn = isbn @isbn = isbn @price = Float(price) @price = Float(price) end end def isbn def price=(new_price) @isbn @price = new_price end end def price @price # .. end end # .. end
  • 25.
    The Ruby Way class BookInStock attr_reader :isbn attr_accessor :price def initialize(isbn, price) @isbn = isbn @price = Float(price) end # ... end
  • 26.
    The Ruby Way class BookInStock attr_reader :isbn attr_accessor :price def initialize(isbn, price) @isbn = isbn @price = Float(price) end # ... end book = BookInStock.new("isbn1", 33.80) puts "ISBN = #{book.isbn}" => ISBN = isbn1
  • 27.
    The Ruby Way class BookInStock attr_reader :isbn attr_accessor :price def initialize(isbn, price) @isbn = isbn @price = Float(price) end # ... end book = BookInStock.new("isbn1", 33.80) puts "ISBN = #{book.isbn}" => ISBN = isbn1 puts "Price = #{book.price}" => Price = 33.8
  • 28.
    The Ruby Way class BookInStock attr_reader :isbn attr_accessor :price def initialize(isbn, price) @isbn = isbn @price = Float(price) end # ... end book = BookInStock.new("isbn1", 33.80) puts "ISBN = #{book.isbn}" => ISBN = isbn1 puts "Price = #{book.price}" => Price = 33.8 book.price = book.price * 0.75 puts "New price = #{book.price}" => New price = 25.349999999999998
  • 29.
  • 30.
    Arrays Een collectie vanobjecten, geïndexeerd door een positieve integer
  • 31.
    Arrays Een collectie vanobjecten, geïndexeerd door een positieve integer a = [ 3.14159, "pie", 99 ] b = Array.new a.class b.class => Array => Array a.length b.length => 3 => 0 a[0] b[0] = "second" => 3.14159 b[1] = "array" a[1] b => "pie" => ["second", "array"] a[2] => 99 a[3] => nil
  • 32.
    Arrays Stacks FIFO stack = [] queue = [] stack.push "red" queue.push "red" stack.push "green" queue.push "green" stack.push "blue" p stack puts queue.shift => ["red", "green", "blue"] => red puts queue.shift puts stack.pop => green => blue puts stack.pop => green puts stack.pop => red p stack => []
  • 33.
    Hashes Een collectie vanobjecten, dat geïndexeerd kan worden door elk objecttype
  • 34.
    Hashes Een collectie vanobjecten, dat geïndexeerd kan worden door elk objecttype h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
  • 35.
    Hashes Een collectie vanobjecten, dat geïndexeerd kan worden door elk objecttype h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' } h = { :dog => 'canine', :cat => 'feline', :donkey => 'asinine' }
  • 36.
    Hashes Een collectie vanobjecten, dat geïndexeerd kan worden door elk objecttype h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' } h = { :dog => 'canine', :cat => 'feline', :donkey => 'asinine' }
  • 37.
    Symbolen Unieke constanten zonderwaarden Eerste karakter “:” gevolgd door een naam Voornamelijk gebruikt als keys voor Hash {:name => “Ruby”} of {name: “Ruby”}
  • 38.
  • 39.
    Blocks en Iterators top_five= {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1}
  • 40.
    Blocks en Iterators top_five= {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1} for i in 0...5 word = top_five[i][0] count = top_five[i][1] puts "#{word}: #{count}" end
  • 41.
    Blocks en Iterators top_five= {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1} for i in 0...5 word = top_five[i][0] count = top_five[i][1] puts "#{word}: #{count}" end top_five.each do |word, count| puts "#{word}: #{count}" end
  • 42.
    Blocks en Iterators top_five= {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1} for i in 0...5 word = top_five[i][0] count = top_five[i][1] puts "#{word}: #{count}" end top_five.each do |word, count| puts "#{word}: #{count}" Block end
  • 43.
    Blocks en Iterators top_five= {“de” => 1, “kat” => 1, “zat” => 1, “op” => 1, “de” => 1, “mat” => 1} for i in 0...5 word = top_five[i][0] count = top_five[i][1] puts "#{word}: #{count}" end top_five.each do |word, count| Iterator puts "#{word}: #{count}" Block end
  • 44.
    Blocks Een stuk codetussen {} of do end keywords Kan parameters meekrijgen tussen | param1 | Parameters zijn altijd gescoped binnen het block Variabelen zijn gescoped binnen een block, behalve als ze buiten het block gedefinieerd staan
  • 45.
    Blocks sum = 0 [1,2, 3, 4].each do |value| square = value * value sum += square end puts sum => 30
  • 46.
    Blocks sum = 0 square = Shape.new(sides: 4) [1, 2, 3, 4].each do |value| # square = value * value # .. een heleboel code sum += square # end sum = 0 puts sum [1, 2, 3, 4].each do |value| => 30 square = value * value sum += square end puts sum square.draw # BOOM!
  • 47.
    Blocks sum = 0 square = Shape.new(sides: 4) [1, 2, 3, 4].each do |value| # square = value * value # .. een heleboel code sum += square # end sum = 0 puts sum [1, 2, 3, 4].each do |value; square| => 30 square = value * value sum += square end puts sum square.draw
  • 48.
  • 49.
    Inheritance class Parent end class Child< Parent end puts "The superclass of Child is #{Child.superclass}" => “The superclass of Child is Parent” puts "The superclass of Parent is #{Parent.superclass}" => “The superclass of Parent is Object” puts "The superclass of Object is #{Object.superclass}" => “The superclass of Object is BasicObject” puts "The superclass of BasicObject is #{BasicObject.superclass.inspect}" => “The superclass of BasicObject is nil”
  • 50.
    Modules Groep van methods,classes en constanten Eigen namespace Kunnen gebruikt worden voor Mixins
  • 51.
    Modules module Trig PI= 3.141592654 def Trig.sin(x) puts x end end module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) puts badness end end
  • 52.
    Modules module Trig PI= 3.141592654 def Trig.sin(x) puts x end end module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) puts badness end end y = Trig.sin(Trig::PI/4) wrongdoing = Moral.sin(Moral::VERY_BAD) => 0.7853981635 => 0
  • 53.
    Modules module Trig PI= 3.141592654 def Trig.sin(x) puts x end Module methods end module Moral VERY_BAD = 0 BAD = 1 def Moral.sin(badness) puts badness end end y = Trig.sin(Trig::PI/4) wrongdoing = Moral.sin(Moral::VERY_BAD) => 0.7853981635 => 0
  • 54.
  • 55.
    Instance methods? moduleDebug def who_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end
  • 56.
    Instance methods? module Debug def who_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end FOUT: Een module is geen Class
  • 57.
    Wat heb jeer dan aan?
  • 58.
    Mixins module Debug defwho_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end
  • 59.
    Mixins module Debug defwho_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end class Phonograph class EightTrack include Debug include Debug attr_reader :name attr_reader :name def initialize(name) def initialize(name) @name = name @name = name end end # ... # ... end end
  • 60.
    Mixins module Debug defwho_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end class Phonograph class EightTrack include Debug include Debug attr_reader :name attr_reader :name def initialize(name) def initialize(name) @name = name @name = name end end # ... # ... end end
  • 61.
    Mixins module Debug defwho_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end class Phonograph class EightTrack include Debug include Debug attr_reader :name attr_reader :name def initialize(name) def initialize(name) @name = name @name = name end end # ... # ... end end ph = Phonograph.new("West End Blues") et = EightTrack.new("Surrealistic Pillow") ph.who_am_i? et.who_am_i?
  • 62.
    Mixins module Debug defwho_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end class Phonograph class EightTrack include Debug include Debug attr_reader :name attr_reader :name def initialize(name) def initialize(name) @name = name @name = name end end # ... # ... end end ph = Phonograph.new("West End Blues") et = EightTrack.new("Surrealistic Pillow") ph.who_am_i? # => "Phonograph (id: 2151894340): West End Blues" et.who_am_i? # => "EightTrack (id: 2151894300): Surrealistic Pillow"
  • 63.
    Include include is alleeneen referentie naar de module Als de module in een ander bestand staat dan is require nodig om de module beschikbaar te maken LET OP: Als een method wijzigt in de module dan wijzigt deze voor alle classes die de module includen
  • 64.
  • 65.
    Methods Worden definieerd metdef Beginnen met een kleine letter of een underscore (_) Kunnen eindigen met een letter of cijfer Kunnen eindigen met een ? (boolean) Kunnen eindigen met een = (setters) Kunnen eindigen met een ! (bang methods)
  • 66.
  • 67.
    Arguments def my_new_method(arg1, arg2,arg3) # ... end def my_other_new_method # ... end
  • 68.
    Arguments def my_new_method(arg1, arg2,arg3) # ... end def my_other_new_method # ... end def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach") "#{arg1}, #{arg2}, #{arg3}." end
  • 69.
    Arguments def my_new_method(arg1, arg2,arg3) # ... end def my_other_new_method # ... end def cool_dude(arg1="Miles", arg2="Coltrane", arg3="Roach") "#{arg1}, #{arg2}, #{arg3}." end def varargs(arg1, *rest) "arg1=#{arg1}. rest=#{rest.inspect}" end
  • 70.
  • 71.
    Expresions Alles dat redelijkerwijseen waarde kan terug geven doet dat ook Bijna alles is een expression
  • 72.
    Expresions [ 3, 1,7, 0 ].sort.reverse # => [7, 3, 1, 0]
  • 73.
    Expresions [ 3, 1,7, 0 ].sort.reverse # => [7, 3, 1, 0] song_type = if song.mp3_type == MP3::Jazz if song.written < Date.new(1935, 1, 1) Song::TradJazz else Song::Jazz end else Song::Other end rating = case votes_cast when 0...10 then Rating::SkipThisOne when 10...50 then Rating::CouldDoBetter else Rating::Rave end
  • 74.
    Vergelijken van objecten == Test dezelfde waarde. === Vergelijk of een element binnen een bepaald berijk valt. (1..10) === 5 <=> Algemene vergelijkingsoperator. Geeft -1 bij kleiner dan, 0 bij gelijk, of +1 bij groter dan <,<=,>=,> Vergelijking voor kleiner dan, kleiner en gelijk, groter dan, groter en gelijk. =~ Reguliere expressie vergelijking eql? True als de elementen dezelfde waarde en type hebben 1.eql?(1.0) is false. equal? True als de elementen dezelfde objectID hebben
  • 75.
    Conditioneel uitvoeren nil &&99 # => nil false && 99 # => false "cat" && 99 # => 99
  • 76.
    Conditioneel uitvoeren nil &&99 # => nil false && 99 # => false "cat" && 99 # => 99 nil || 99 # => 99 false || 99 # => 99 "cat" || 99 # => "cat"
  • 77.
    Conditioneel uitvoeren nil &&99 # => nil var ||= "default value" false && 99 # => false "cat" && 99 # => 99 nil || 99 # => 99 false || 99 # => 99 "cat" || 99 # => "cat"
  • 78.
    Conditioneel uitvoeren nil &&99 # => nil var ||= "default value" false && 99 # => false "cat" && 99 # => 99 nil || 99 # => 99 month, day, year = $1, $2, $3 if date =~ /(dd)-(dd)-(dd)/ false || 99 # => 99 puts "a = #{a}" if DEBUG "cat" || 99 # => "cat" print total unless total.zero?
  • 79.
    Conditioneel uitvoeren nil &&99 # => nil var ||= "default value" false && 99 # => false "cat" && 99 # => 99 nil || 99 # => 99 month, day, year = $1, $2, $3 if date =~ /(dd)-(dd)-(dd)/ false || 99 # => 99 puts "a = #{a}" if $DEBUG "cat" || 99 # => "cat" print total unless total.zero? cost = duration > 180 ? 0.35 : 0.25
  • 80.
  • 81.
    Loops? while line =gets # ... end
  • 82.
    Loops? until play_list.duration > 60 while line = gets play_list.add(song_list.pop) # ... end end
  • 83.
    Iterators 3.times do print "Ho! " end => Ho! Ho! Ho!
  • 84.
    Iterators 3.times do print "Ho! " end => Ho! Ho! Ho! 0.step(12, 3) {|x| print x, " " } => 0 3 6 9 12
  • 85.
    Iterators 3.times do print "Ho! " end => Ho! Ho! Ho! 0.step(12, 3) {|x| print x, " " } => 0 3 6 9 12 File.open("ordinal").grep(/d$/) do |line| puts line end
  • 86.
    Iterators 3.times do 0.upto(9) do |x| print "Ho! " print x, " " end end => Ho! Ho! Ho! => 0 1 2 3 4 5 6 7 8 9 0.step(12, 3) {|x| print x, " " } => 0 3 6 9 12 File.open("ordinal").grep(/d$/) do |line| puts line end
  • 87.
    Iterators 3.times do 0.upto(9) do |x| print "Ho! " print x, " " end end => Ho! Ho! Ho! => 0 1 2 3 4 5 6 7 8 9 0.step(12, 3) {|x| print x, " " } [ 1, 1, 2, 3, 5 ].each {|val| print val, " " } => 0 3 6 9 12 => 1 1 2 3 5 File.open("ordinal").grep(/d$/) do |line| puts line end
  • 88.
    Iterators 3.times do 0.upto(9) do |x| print "Ho! " print x, " " end end => Ho! Ho! Ho! => 0 1 2 3 4 5 6 7 8 9 0.step(12, 3) {|x| print x, " " } [ 1, 1, 2, 3, 5 ].each {|val| print val, " " } => 0 3 6 9 12 => 1 1 2 3 5 File.open("ordinal").grep(/d$/) do |line| playlist.each do |song| puts line song.play end end
  • 89.
  • 90.
    Exceptions require 'open-uri' page ="podcasts" file_name = "#{page}.html" web_page = open("http:/ /pragprog.com/#{page}") output = File.open(file_name, "w") while line = web_page.gets output.puts line end output.close
  • 91.
    Exceptions require 'open-uri' page ="podcasts" file_name = "#{page}.html" web_page = open("http:/ /pragprog.com/#{page}") output = File.open(file_name, "w") begin while line = web_page.gets output.puts line end output.close rescue Exception STDERR.puts "Failed to download #{page}: #{$!}" output.close File.delete(file_name) raise end
  • 92.
  • 93.
  • 94.
    Opdrachten Verhaalgenerator Crazy 8-Ball Spel Steen,papier, schaar Blackjack Spel Boter, Kaas en Eieren Spel