SlideShare une entreprise Scribd logo
1  sur  94
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

Contenu connexe

Tendances

FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101Faisal Abid
 
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...takeoutweight
 
Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014Puppet
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersGiovanni924
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 
Template Haskell Tutorial
Template Haskell TutorialTemplate Haskell Tutorial
Template Haskell Tutorialkizzx2
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 
Switching from java to groovy
Switching from java to groovySwitching from java to groovy
Switching from java to groovyPaul Woods
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.VimLin Yo-An
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to GroovyAnton Arhipov
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of AtrocityMichael Pirnat
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 WorldDaniel Blyth
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQLCarlos Hernando
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 

Tendances (18)

FITC CoffeeScript 101
FITC CoffeeScript 101FITC CoffeeScript 101
FITC CoffeeScript 101
 
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...
Haste (Same Language, Multiple Platforms) and Tagless Final Style (Same Synta...
 
Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Template Haskell Tutorial
Template Haskell TutorialTemplate Haskell Tutorial
Template Haskell Tutorial
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
Switching from java to groovy
Switching from java to groovySwitching from java to groovy
Switching from java to groovy
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Exhibition of Atrocity
Exhibition of AtrocityExhibition of Atrocity
Exhibition of Atrocity
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 World
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Introducción rápida a SQL
Introducción rápida a SQLIntroducción rápida a SQL
Introducción rápida a SQL
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 

En vedette

Principles of usability
Principles of usabilityPrinciples of usability
Principles of usabilityLuis Doubrava
 
Pi planning using hdm 25 nov moldova (rom)
Pi planning using hdm 25 nov moldova (rom)Pi planning using hdm 25 nov moldova (rom)
Pi planning using hdm 25 nov moldova (rom)Hamid62
 
Een terugblik op Fronteers 2014
Een terugblik op Fronteers 2014Een terugblik op Fronteers 2014
Een terugblik op Fronteers 2014Luis Doubrava
 
Skyline presentation
Skyline presentationSkyline presentation
Skyline presentationLuis Doubrava
 
Sustainable Development and Global Practice (SDGP): Educating Professionals f...
Sustainable Development and Global Practice (SDGP): Educating Professionals f...Sustainable Development and Global Practice (SDGP): Educating Professionals f...
Sustainable Development and Global Practice (SDGP): Educating Professionals f...Global Risk Forum GRFDavos
 

En vedette (7)

Principles of usability
Principles of usabilityPrinciples of usability
Principles of usability
 
The Rails way
The Rails wayThe Rails way
The Rails way
 
Pi planning using hdm 25 nov moldova (rom)
Pi planning using hdm 25 nov moldova (rom)Pi planning using hdm 25 nov moldova (rom)
Pi planning using hdm 25 nov moldova (rom)
 
Een terugblik op Fronteers 2014
Een terugblik op Fronteers 2014Een terugblik op Fronteers 2014
Een terugblik op Fronteers 2014
 
Mobile media
Mobile mediaMobile media
Mobile media
 
Skyline presentation
Skyline presentationSkyline presentation
Skyline presentation
 
Sustainable Development and Global Practice (SDGP): Educating Professionals f...
Sustainable Development and Global Practice (SDGP): Educating Professionals f...Sustainable Development and Global Practice (SDGP): Educating Professionals f...
Sustainable Development and Global Practice (SDGP): Educating Professionals f...
 

Similaire à 1 the ruby way

Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kirill Rozov
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyGautam Rege
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in pythonJohn(Qiang) Zhang
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Tudor Girba
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)intelliyole
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python Meetup
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionariesMarc Gouw
 

Similaire à 1 the ruby way (20)

Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
ScotRuby - Dark side of ruby
ScotRuby - Dark side of rubyScotRuby - Dark side of ruby
ScotRuby - Dark side of ruby
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
 
Ruby Classes
Ruby ClassesRuby Classes
Ruby Classes
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011
 
Ruby
RubyRuby
Ruby
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Basic swift
Basic swiftBasic swift
Basic swift
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
 
Class 6: Lists & dictionaries
Class 6: Lists & dictionariesClass 6: Lists & dictionaries
Class 6: Lists & dictionaries
 

Dernier

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Dernier (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

1 the ruby way

  • 1. Programmeren met Ruby The Ruby Way 1
  • 5. .rb files > ruby mijn_script.rb
  • 7. 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
  • 8. 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
  • 10. Duck typing “Als een Object 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)
  • 14. 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>
  • 15. 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>
  • 16. 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
  • 17. 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
  • 19. Instance variabelen instance variabelen zijn private Alleen het object zelf kan ze manipuleren
  • 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
  • 30. Arrays Een collectie van objecten, geïndexeerd door een positieve integer
  • 31. 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
  • 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 van objecten, dat geïndexeerd kan worden door elk objecttype
  • 34. Hashes Een collectie van objecten, dat geïndexeerd kan worden door elk objecttype h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' }
  • 35. 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' }
  • 36. 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' }
  • 37. Symbolen Unieke constanten zonder waarden Eerste karakter “:” gevolgd door een naam Voornamelijk gebruikt als keys voor Hash {:name => “Ruby”} of {name: “Ruby”}
  • 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 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
  • 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
  • 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
  • 55. Instance methods? module Debug 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 je er dan aan?
  • 58. Mixins module Debug def who_am_i? "#{self.class.name} (id: #{self.object_id}): #{self.name}" end end
  • 59. 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
  • 60. 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
  • 61. 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?
  • 62. 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"
  • 63. 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
  • 65. 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)
  • 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
  • 71. Expresions Alles dat redelijkerwijs een 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
  • 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
  • 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
  • 94. Opdrachten Verhaalgenerator Crazy 8-Ball Spel Steen, papier, schaar Blackjack Spel Boter, Kaas en Eieren Spel

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n