SlideShare a Scribd company logo
Úvod do programování aneb Do nitra stroje
PŘEDNÁŠKA                       Karel Minařík
            5
1   Opakování




                Úvod do programování
ZÁKLADNÍ KONCEPTY

1. Datové typy: čísla, texty, pole, hashe; Přetypování

2. Proměnné a rozsah platnosti

3. Metody a funkce

4. Podmínky a logické operátory
5. Smyčky a iterátory

6. Výjimky — ošetření chyb

7. Vstup

8. Výstup




                                                         Úvod do programování Přednáška 5
vyjimky.rb


require 'net/http'

server = 'www.lidovky.cz'   # vs. www.neexistuje.cz nebo vytazeny sitovy kabel...


begin
  response, data = Net::HTTP.new(server).get('/')
rescue Exception
  puts quot;Nemohu se připojit na server #{server}quot;
  # ...načteme data uložená na disku...
  # data = ...
end
puts data.to_s.scan(
    /<div class=quot;art openerquot;><h3><a href=quot;.+quot;>(.*)</a></h3>/).to_s
  ) if data




                                                              Úvod do programování Přednáška 5
parsovani_html.rb


require   'rubygems'
require   'hpricot'
require   'open-uri'
require   'iconv'

server = 'http://www.lidovky.cz'   # vs. www.neexistuje.cz nebo vytazeny sitovy kabel...



begin
  html = Hpricot( open(server) )
rescue Exception
  puts quot;Nemohu se připojit na server #{server}...quot;
  exit
end


             html.search('div.art.opener h3 a').inner_html
titulek =

puts Iconv.iconv( 'utf-8', 'windows-1250', titulek )




                                                                  Úvod do programování Přednáška 5
parsovani_html.rb

require    'rubygems'
require    'hpricot'
require    'open-uri'
require    'iconv'

server = 'http://www.lidovky.cz' # vs. www.neexistuje.cz nebo vytazeny sitovy kabel...

begin
            Hpricot(
  html =                 open(server) )
rescue Exception
  puts quot;Nemohu se připojit na server #{server}...quot;
  exit
end


             html.search('div.art.opener h3 a').inner_html
titulek =


puts Iconv.iconv( 'utf-8', 'windows-1250', titulek )




                        http://code.whytheluckystiff.net/hpricot/
                        www.igvita.com/blog/2007/02/04/ruby-screen-scraper-in-60-seconds/




                                                                                  Úvod do programování Přednáška 5
nejpouzivanejsi_slovo.rb

text = File.read 'kafka_promena.txt'

# ---> A ted neco trochu jineho... Najdeme nejpouzivanejsi slovo :)


words   = text.tr('-,();'quot;', '').split(' ')


current_word = words.sort.first

word_counts = {}
word_counts[current_word] = {}

count = 0


words.sort.each do |word|
  if word == current_word
    count += 1
  else
    count = 1
    current_word = word
  end
  word_counts[word]           = {:word => word, :count => count}


                                         Když se Řehoř Samsa
end

nejpouzivanejsi = word_counts.sort.first           # quot;Nejvetsi = prvniquot; -- [quot;Aquot;, {:count=>37, :word=>quot;Aquot;}]



                                         nepokojných snů, shle
puts quot;Začínáme s quot; + nejpouzivanejsi[1][:word].to_s + quot;.quot;

word_counts.sort.each do |word|



                                         proměnil v jakýsi nestv
  nejpouzivanejsi = word if word[1][:count] > nejpouzivanejsi[1][:count]
end



puts quot;Nejpoužívanější slovo je „quot; + nejpouzivanejsi[1][:word] + quot;“ s quot; + nejpouzivanejsi[1][:count].to_s + quot; výskyty.quot;



                                                                                         Úvod do programování Přednáška 5
seznam_nejpouzivanejsich_slov.rb

text = File.read 'kafka_promena.txt'

# ---> ... a co seznam slov podle frekvence pouziti?

puts quot;Seznam nejpoužívanějších slov v Kafkově ‚Proměně‘:quot;

most_frequent_words = word_counts.values.collect { |word| [word[:count], word
[:word]] }

most_frequent_words.sort.reverse.each_with_index do |word, i|
  puts quot;#{i+1}. #{word[1]}ttt(#{word[0]} výskytů)quot;
end




                                     Když se Řehoř Samsa
                                     nepokojných snů, shle
                                     proměnil v jakýsi nestv
                                                        Úvod do programování Přednáška 5
nejpouzivanejsi_slovo.rb

1   text = File.read 'kafka_promena.txt'

    # ---> A ted neco trochu jineho... Najdeme nejpouzivanejsi slovo :)


    words   = text.tr('-,();'quot;', '').split(' ')


    current_word = words.sort.first
2
    word_counts = {}
    word_counts[current_word] = {}

    count = 0


    words.sort.each do |word|
      if word == current_word
        count += 1
3     else
        count = 1
        current_word = word
      end
      word_counts[word]           = {:word => word, :count => count}


                                             Když se Řehoř Samsa
    end

    nejpouzivanejsi = word_counts.sort.first           # quot;Nejvetsi = prvniquot; -- [quot;Aquot;, {:count=>37, :word=>quot;Aquot;}]



                                             nepokojných snů, shle
    puts quot;Začínáme s quot; + nejpouzivanejsi[1][:word].to_s + quot;.quot;

    word_counts.sort.each do |word|



                                             proměnil v jakýsi nestv
      nejpouzivanejsi = word if word[1][:count] > nejpouzivanejsi[1][:count]
4
    end



    puts quot;Nejpoužívanější slovo je „quot; + nejpouzivanejsi[1][:word] + quot;“ s quot; + nejpouzivanejsi[1][:count].to_s + quot; výskyty.quot;



                                                                                             Úvod do programování Přednáška 5
„Křehký kód“
 „Fragile code“




                  Úvod do programování Přednáška 5
2   Objektově orientované programování




                                         Úvod do programování
1. Nalít olej do pánve
2. Zapálit plyn
3. Vzít vejce
4. Rozklepnout vejce o okraj pánve




                      Úvod do programování Přednáška 5
1. Nalít olej do pánve
2. Zapálit plyn
3. Vzít vejce, sůl a pepř
4. Rozklepnout vejce o okraj pánve




                      Úvod do programování Přednáška 5
„Udržovatelnost“ software

     Znovu-použití
        Re-usability

      Rozšiřitelnost




                       Úvod do programování Přednáška 5
Košík      Produkty




Objednávky   Diskuse


  Platby




                        Úvod do programování Přednáška 5
Customer.php
~500 řádků kódu

                    Košík      Produkty




                  Objednávky   Diskuse


                    Platby




                                          Úvod do programování Přednáška 5
Customer.php
~500 řádků kódu

                    Košík      Produkty




                  Objednávky   Diskuse


                    Platby




                                          Úvod do programování Přednáška 5
ZÁKLADNÍ KONCEPTY OBJEKTOVĚ ORIENTOVANÉHO PROGRAMOVÁNÍ (OOP)

1. Zapouzdření Encapsulation

2. Modulárnost Modularity

3. Dědičnost Inheritance

4. Rozhraní Interface
5. Abstraktnost Abstraction

6. Polymorfie Polymorfism




                                              Úvod do programování Přednáška 5
„Formičky“
Zvíře




Pes           Ovce




                     Úvod do programování Přednáška 5
animals.rb

 1   require 'pp'
 2
 3   # *** ANIMALS *****************************************************************
 4
 5   #-- file Animal.rb
 6   class Animal
 7
 8     attr_accessor :name, :position, :color
 9
10     def initialize(name)
11       @name = name
12       @position = 0
13       @stuff_in_belly = 0
14       @walk_increment = 1
15       @run_increment = 10
16       puts quot;Hello, I am a #{self.class.to_s.downcase} named #{self.name}!quot;
17     end
18
19     def talk
20       puts quot;#{self.class}: ...quot;
21
22     end
23




                                                                   Úvod do programování Přednáška 5
animals.rb

24   def walk
25     @position += @walk_increment
26   end
27
28   def run
29     @position += @run_increment
30   end
31
32   def feed
33     @stuff_in_belly += 1
34     puts quot;[Chewing on some stuff and happy...]quot;
35     self.poop if @stuff_in_belly > 3
36   end
37
38   def hungry?
39     if @stuff_in_belly < 2
40       true
41     else
42       false
43     end
44   end
45




                                                     Úvod do programování Přednáška 5
animals.rb

46   protected
47
48   def poop
49     puts quot;[Too much stuff in belly... pooping...]quot;
50     @stuff_in_belly = 0
51   end
52
53 end
54
55




                                                        Úvod do programování Přednáška 5
animals.rb

56 #-- file Dog.rb
57 class Dog < Animal
58
59   def initialize(name, color)
60     super(name)
61     @color = color
62     @run_increment = 20
63
64   end
65
66   def talk
67     puts quot;#{self.name}: Woof! woof!quot;
68   end
69
70   def fetch(what='stick')
71     puts quot;[#{self.name} is fetching the #{what.downcase}...]quot;
72   end
73
74 end
75
76




                                                                   Úvod do programování Přednáška 5
animals.rb

77 #-- file Sheep.rb
78 class Sheep < Animal
79
80   def talk
81     puts quot;#{self.name}: Beeeeee!quot;
82   end
83
84 end
85




                                       Úvod do programování Přednáška 5
animals.rb

86   # === Dog =====================================================================
87
88   # --- Create a dog
89   dog = Dog.new('Bitzer', 'yellow')
90   pp dog
91
92   # --- Dog's properties (attributes)
93   puts quot;Our dog's name is '#{dog.name}'.quot;
94   puts quot;And his color is #{dog.color}.quot;
95




                                                                   Úvod do programování Přednáška 5
animals.rb

 96   # --- Make the dog do something
 97   puts quot;> Talk, Bitzer!quot;
 98   dog.talk
 99
100   puts quot;> Fetch, Bitzer!quot;
101   dog.fetch
102   dog.fetch('Ball')
103
104   puts quot;> Walk, Bitzer!quot;
105   dog.walk
106   puts quot;Dog is at position: #{dog.position}.quot;
107   puts quot;> Run, Bitzer!quot;
108   dog.run
109   puts quot;Dog is at position: #{dog.position}.quot;
110
111   puts quot;> Have a snack, Bitzer!quot;
112   dog.feed
113   puts dog.hungry?
114
115   dog.feed
116   dog.feed
117   puts dog.hungry?
118
119   # dog.poop
120   dog.feed
121
122




                                                    Úvod do programování Přednáška 5
animals.rb

123   puts quot;n---nnquot;
124   # === Sheep ===================================================================
125
126   sheep = Sheep.new('Shaun')
127   pp sheep
128
129   sheep.talk
130
131   puts sheep.position
132   sheep.run
133   puts sheep.position
134
135   # sheep.fetch




                                                                    Úvod do programování Přednáška 5
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html



                                                   Úvod do programování Přednáška 5
DOMÁCÍ ÚKOL

Navrhněte a naprogramujte třídu TextAnalyzer

TextAnalyzer:
  text
•
• characters
• words
• pages
• unique_words
• most_frequent_words
• most_frequent_word




                                        Úvod do programování Přednáška 5
Návrhové vzory
 Design patterns




                   Úvod do programování Přednáška 5
PŘÍKLAD
Návrhový vzor ActiveRecord
tabulka people
  ID           Name                   Surname                     E-mail
   1            John                   Smith                smith@hotmail.com
   2          Susanna                 Reddick                susan@yahoo.com




INSERT INTO people (name, surname, email) VALUES( 'John', 'Smith', 'smith@hotmail.com' );
SELECT * FROM people;
SELECT * FROM people WHERE id = 1;
SELECT * FROM people WHERE surname = 'Smith';



# ActiveRecord::Base.establish_connection ..
Person.create(:name => 'John', :surname => 'Smith', :email => 'smith@hotmail.com')
Person.find(:all)
Person.find(1)
Person.find_by_name('Smith')




                                                                       Úvod do programování Přednáška 5
PŘÍKLAD
Návrhový vzor ActiveRecord

require 'rubygems'
require_gem 'activerecord'
require 'pp'

ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => 'active_record_test.db')
ActiveRecord::Base.connection.execute('CREATE TABLE quot;peoplequot; ( id INTEGER PRIMARY KEY NOT NULL, name VARCHAR
(255), surname VARCHAR(255), email VARCHAR(255) )')


class Person < ActiveRecord::Base
end

Person.create( :name => 'John', :surname => 'Smith', :email => 'smith@hotmail.com' )
Person.create( :name => 'Susanna', :surname => 'Reddick', :email => 'susan@hotmail.com'                )

pp Person.find(:all)
puts quot;nquot;


pp Person.find(1)
puts quot;nquot;


pp Person.find_by_surname('Smith')
puts quot;nquot;




                                                                                             Úvod do programování Přednáška 5
MODELOVÁNÍ
Unified Modeling Language (UML)




                                  Úvod do programování Přednáška 5
Děkuji!
 

More Related Content

What's hot

Phone calls and sms from php
Phone calls and sms from phpPhone calls and sms from php
Phone calls and sms from php
David Stockton
 
Review unknown code with static analysis Zend con 2017
Review unknown code with static analysis  Zend con 2017Review unknown code with static analysis  Zend con 2017
Review unknown code with static analysis Zend con 2017
Damien Seguy
 
A3 sec -_regular_expressions
A3 sec -_regular_expressionsA3 sec -_regular_expressions
A3 sec -_regular_expressionsa3sec
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
Wim Godden
 
Admins: Smoke Test Your Hadoop Cluster!
Admins: Smoke Test Your Hadoop Cluster!Admins: Smoke Test Your Hadoop Cluster!
Admins: Smoke Test Your Hadoop Cluster!
Michael Arnold
 
Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2nottings
 
Joomla! security 101
Joomla! security 101Joomla! security 101
Joomla! security 101vdrover
 
Perl web app 테스트전략
Perl web app 테스트전략Perl web app 테스트전략
Perl web app 테스트전략
Jeen Lee
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 
PHP Performance SfLive 2010
PHP Performance SfLive 2010PHP Performance SfLive 2010
PHP Performance SfLive 2010
De Cock Xavier
 
Power shell voor developers
Power shell voor developersPower shell voor developers
Power shell voor developers
Dennis Vroegop
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2Dave Cross
 
Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1Shinya Ohyanagi
 
PuppetCamp Ghent - What Not to Do with Puppet
PuppetCamp Ghent - What Not to Do with PuppetPuppetCamp Ghent - What Not to Do with Puppet
PuppetCamp Ghent - What Not to Do with Puppet
Walter Heck
 
Parse Everything With Elixir
Parse Everything With ElixirParse Everything With Elixir
Parse Everything With Elixir
Gabriele Lana
 
Puppet: What _not_ to do
Puppet: What _not_ to doPuppet: What _not_ to do
Puppet: What _not_ to do
Puppet
 
Phing all the things
Phing all the thingsPhing all the things
Phing all the things
Omni Adams
 
Percona toolkit
Percona toolkitPercona toolkit
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.key
Tim Bunce
 

What's hot (20)

Phone calls and sms from php
Phone calls and sms from phpPhone calls and sms from php
Phone calls and sms from php
 
Five
FiveFive
Five
 
Review unknown code with static analysis Zend con 2017
Review unknown code with static analysis  Zend con 2017Review unknown code with static analysis  Zend con 2017
Review unknown code with static analysis Zend con 2017
 
A3 sec -_regular_expressions
A3 sec -_regular_expressionsA3 sec -_regular_expressions
A3 sec -_regular_expressions
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Admins: Smoke Test Your Hadoop Cluster!
Admins: Smoke Test Your Hadoop Cluster!Admins: Smoke Test Your Hadoop Cluster!
Admins: Smoke Test Your Hadoop Cluster!
 
Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2Puppet camp chicago-automated_testing2
Puppet camp chicago-automated_testing2
 
Joomla! security 101
Joomla! security 101Joomla! security 101
Joomla! security 101
 
Perl web app 테스트전략
Perl web app 테스트전략Perl web app 테스트전략
Perl web app 테스트전략
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
PHP Performance SfLive 2010
PHP Performance SfLive 2010PHP Performance SfLive 2010
PHP Performance SfLive 2010
 
Power shell voor developers
Power shell voor developersPower shell voor developers
Power shell voor developers
 
Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1Zend Framework Study@Tokyo vol1
Zend Framework Study@Tokyo vol1
 
PuppetCamp Ghent - What Not to Do with Puppet
PuppetCamp Ghent - What Not to Do with PuppetPuppetCamp Ghent - What Not to Do with Puppet
PuppetCamp Ghent - What Not to Do with Puppet
 
Parse Everything With Elixir
Parse Everything With ElixirParse Everything With Elixir
Parse Everything With Elixir
 
Puppet: What _not_ to do
Puppet: What _not_ to doPuppet: What _not_ to do
Puppet: What _not_ to do
 
Phing all the things
Phing all the thingsPhing all the things
Phing all the things
 
Percona toolkit
Percona toolkitPercona toolkit
Percona toolkit
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.key
 

Viewers also liked

Historie programovacích jazyků
Historie programovacích jazykůHistorie programovacích jazyků
Historie programovacích jazyků
Karel Minarik
 
Úvod do programování 4
Úvod do programování 4Úvod do programování 4
Úvod do programování 4
Karel Minarik
 
Úvod do programování 6
Úvod do programování 6Úvod do programování 6
Úvod do programování 6
Karel Minarik
 
Úvod do programování 7
Úvod do programování 7Úvod do programování 7
Úvod do programování 7
Karel Minarik
 
Verzovani kodu s Gitem (Karel Minarik)
Verzovani kodu s Gitem (Karel Minarik)Verzovani kodu s Gitem (Karel Minarik)
Verzovani kodu s Gitem (Karel Minarik)
Karel Minarik
 
Vizualizace dat a D3.js [EUROPEN 2014]
Vizualizace dat a D3.js [EUROPEN 2014]Vizualizace dat a D3.js [EUROPEN 2014]
Vizualizace dat a D3.js [EUROPEN 2014]
Karel Minarik
 
Git CZ
Git CZGit CZ
Git CZ
Miloš Janda
 
Úvod do programování 3 (to be continued)
Úvod do programování 3 (to be continued)Úvod do programování 3 (to be continued)
Úvod do programování 3 (to be continued)Karel Minarik
 
Úvod do programování aneb Do nitra stroje
Úvod do programování aneb Do nitra strojeÚvod do programování aneb Do nitra stroje
Úvod do programování aneb Do nitra stroje
Karel Minarik
 

Viewers also liked (9)

Historie programovacích jazyků
Historie programovacích jazykůHistorie programovacích jazyků
Historie programovacích jazyků
 
Úvod do programování 4
Úvod do programování 4Úvod do programování 4
Úvod do programování 4
 
Úvod do programování 6
Úvod do programování 6Úvod do programování 6
Úvod do programování 6
 
Úvod do programování 7
Úvod do programování 7Úvod do programování 7
Úvod do programování 7
 
Verzovani kodu s Gitem (Karel Minarik)
Verzovani kodu s Gitem (Karel Minarik)Verzovani kodu s Gitem (Karel Minarik)
Verzovani kodu s Gitem (Karel Minarik)
 
Vizualizace dat a D3.js [EUROPEN 2014]
Vizualizace dat a D3.js [EUROPEN 2014]Vizualizace dat a D3.js [EUROPEN 2014]
Vizualizace dat a D3.js [EUROPEN 2014]
 
Git CZ
Git CZGit CZ
Git CZ
 
Úvod do programování 3 (to be continued)
Úvod do programování 3 (to be continued)Úvod do programování 3 (to be continued)
Úvod do programování 3 (to be continued)
 
Úvod do programování aneb Do nitra stroje
Úvod do programování aneb Do nitra strojeÚvod do programování aneb Do nitra stroje
Úvod do programování aneb Do nitra stroje
 

Similar to Úvod do programování 5

Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
worr1244
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Wen-Tien Chang
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
Benjamin Bock
 
I, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 OverlordsI, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 Overlords
heumann
 
Refactoring terraform
Refactoring terraformRefactoring terraform
Refactoring terraform
Nell Shamrell-Harrington
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
Kent Cowgill
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
gsterndale
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
brian d foy
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
Brian Hogan
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
brian d foy
 
Arulalan Ruby An Intro
Arulalan  Ruby An IntroArulalan  Ruby An Intro
Arulalan Ruby An Intro
Arulalan T
 
An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to Raku
Simon Proctor
 
Perl basics for Pentesters
Perl basics for PentestersPerl basics for Pentesters
Perl basics for Pentesters
Sanjeev Kumar Jaiswal
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleAnton Shemerey
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
Wes Oldenbeuving
 
Ruby An Introduction
Ruby An IntroductionRuby An Introduction
Ruby An Introduction
Shrinivasan T
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
 

Similar to Úvod do programování 5 (20)

Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
I, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 OverlordsI, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 Overlords
 
Refactoring terraform
Refactoring terraformRefactoring terraform
Refactoring terraform
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
Arulalan Ruby An Intro
Arulalan  Ruby An IntroArulalan  Ruby An Intro
Arulalan Ruby An Intro
 
An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to Raku
 
Perl basics for Pentesters
Perl basics for PentestersPerl basics for Pentesters
Perl basics for Pentesters
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby An Introduction
Ruby An IntroductionRuby An Introduction
Ruby An Introduction
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Ruby
RubyRuby
Ruby
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 

More from Karel Minarik

Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)
Karel Minarik
 
Elasticsearch in 15 Minutes
Elasticsearch in 15 MinutesElasticsearch in 15 Minutes
Elasticsearch in 15 Minutes
Karel Minarik
 
Realtime Analytics With Elasticsearch [New Media Inspiration 2013]
Realtime Analytics With Elasticsearch [New Media Inspiration 2013]Realtime Analytics With Elasticsearch [New Media Inspiration 2013]
Realtime Analytics With Elasticsearch [New Media Inspiration 2013]
Karel Minarik
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Karel Minarik
 
Shell's Kitchen: Infrastructure As Code (Webexpo 2012)
Shell's Kitchen: Infrastructure As Code (Webexpo 2012)Shell's Kitchen: Infrastructure As Code (Webexpo 2012)
Shell's Kitchen: Infrastructure As Code (Webexpo 2012)
Karel Minarik
 
Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)
Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)
Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)
Karel Minarik
 
Your Data, Your Search, ElasticSearch (EURUKO 2011)
Your Data, Your Search, ElasticSearch (EURUKO 2011)Your Data, Your Search, ElasticSearch (EURUKO 2011)
Your Data, Your Search, ElasticSearch (EURUKO 2011)
Karel Minarik
 
Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesKarel Minarik
 
CouchDB – A Database for the Web
CouchDB – A Database for the WebCouchDB – A Database for the Web
CouchDB – A Database for the Web
Karel Minarik
 
Spoiling The Youth With Ruby (Euruko 2010)
Spoiling The Youth With Ruby (Euruko 2010)Spoiling The Youth With Ruby (Euruko 2010)
Spoiling The Youth With Ruby (Euruko 2010)
Karel Minarik
 
Představení Ruby on Rails [Junior Internet]
Představení Ruby on Rails [Junior Internet]Představení Ruby on Rails [Junior Internet]
Představení Ruby on Rails [Junior Internet]
Karel Minarik
 
Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)
Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)
Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)
Karel Minarik
 
Úvod do Ruby on Rails
Úvod do Ruby on RailsÚvod do Ruby on Rails
Úvod do Ruby on Rails
Karel Minarik
 
Interaktivita, originalita a návrhové vzory
Interaktivita, originalita a návrhové vzoryInteraktivita, originalita a návrhové vzory
Interaktivita, originalita a návrhové vzory
Karel Minarik
 

More from Karel Minarik (14)

Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)Elasticsearch (Rubyshift 2013)
Elasticsearch (Rubyshift 2013)
 
Elasticsearch in 15 Minutes
Elasticsearch in 15 MinutesElasticsearch in 15 Minutes
Elasticsearch in 15 Minutes
 
Realtime Analytics With Elasticsearch [New Media Inspiration 2013]
Realtime Analytics With Elasticsearch [New Media Inspiration 2013]Realtime Analytics With Elasticsearch [New Media Inspiration 2013]
Realtime Analytics With Elasticsearch [New Media Inspiration 2013]
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]
 
Shell's Kitchen: Infrastructure As Code (Webexpo 2012)
Shell's Kitchen: Infrastructure As Code (Webexpo 2012)Shell's Kitchen: Infrastructure As Code (Webexpo 2012)
Shell's Kitchen: Infrastructure As Code (Webexpo 2012)
 
Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)
Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)
Elastic Search: Beyond Ordinary Fulltext Search (Webexpo 2011 Prague)
 
Your Data, Your Search, ElasticSearch (EURUKO 2011)
Your Data, Your Search, ElasticSearch (EURUKO 2011)Your Data, Your Search, ElasticSearch (EURUKO 2011)
Your Data, Your Search, ElasticSearch (EURUKO 2011)
 
Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational Databases
 
CouchDB – A Database for the Web
CouchDB – A Database for the WebCouchDB – A Database for the Web
CouchDB – A Database for the Web
 
Spoiling The Youth With Ruby (Euruko 2010)
Spoiling The Youth With Ruby (Euruko 2010)Spoiling The Youth With Ruby (Euruko 2010)
Spoiling The Youth With Ruby (Euruko 2010)
 
Představení Ruby on Rails [Junior Internet]
Představení Ruby on Rails [Junior Internet]Představení Ruby on Rails [Junior Internet]
Představení Ruby on Rails [Junior Internet]
 
Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)
Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)
Efektivni vyvoj webovych aplikaci v Ruby on Rails (Webexpo)
 
Úvod do Ruby on Rails
Úvod do Ruby on RailsÚvod do Ruby on Rails
Úvod do Ruby on Rails
 
Interaktivita, originalita a návrhové vzory
Interaktivita, originalita a návrhové vzoryInteraktivita, originalita a návrhové vzory
Interaktivita, originalita a návrhové vzory
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 

Úvod do programování 5

  • 1. Úvod do programování aneb Do nitra stroje PŘEDNÁŠKA Karel Minařík 5
  • 2. 1 Opakování Úvod do programování
  • 3. ZÁKLADNÍ KONCEPTY 1. Datové typy: čísla, texty, pole, hashe; Přetypování 2. Proměnné a rozsah platnosti 3. Metody a funkce 4. Podmínky a logické operátory 5. Smyčky a iterátory 6. Výjimky — ošetření chyb 7. Vstup 8. Výstup Úvod do programování Přednáška 5
  • 4. vyjimky.rb require 'net/http' server = 'www.lidovky.cz' # vs. www.neexistuje.cz nebo vytazeny sitovy kabel... begin response, data = Net::HTTP.new(server).get('/') rescue Exception puts quot;Nemohu se připojit na server #{server}quot; # ...načteme data uložená na disku... # data = ... end puts data.to_s.scan( /<div class=quot;art openerquot;><h3><a href=quot;.+quot;>(.*)</a></h3>/).to_s ) if data Úvod do programování Přednáška 5
  • 5. parsovani_html.rb require 'rubygems' require 'hpricot' require 'open-uri' require 'iconv' server = 'http://www.lidovky.cz' # vs. www.neexistuje.cz nebo vytazeny sitovy kabel... begin html = Hpricot( open(server) ) rescue Exception puts quot;Nemohu se připojit na server #{server}...quot; exit end html.search('div.art.opener h3 a').inner_html titulek = puts Iconv.iconv( 'utf-8', 'windows-1250', titulek ) Úvod do programování Přednáška 5
  • 6. parsovani_html.rb require 'rubygems' require 'hpricot' require 'open-uri' require 'iconv' server = 'http://www.lidovky.cz' # vs. www.neexistuje.cz nebo vytazeny sitovy kabel... begin Hpricot( html = open(server) ) rescue Exception puts quot;Nemohu se připojit na server #{server}...quot; exit end html.search('div.art.opener h3 a').inner_html titulek = puts Iconv.iconv( 'utf-8', 'windows-1250', titulek ) http://code.whytheluckystiff.net/hpricot/ www.igvita.com/blog/2007/02/04/ruby-screen-scraper-in-60-seconds/ Úvod do programování Přednáška 5
  • 7. nejpouzivanejsi_slovo.rb text = File.read 'kafka_promena.txt' # ---> A ted neco trochu jineho... Najdeme nejpouzivanejsi slovo :) words = text.tr('-,();'quot;', '').split(' ') current_word = words.sort.first word_counts = {} word_counts[current_word] = {} count = 0 words.sort.each do |word| if word == current_word count += 1 else count = 1 current_word = word end word_counts[word] = {:word => word, :count => count} Když se Řehoř Samsa end nejpouzivanejsi = word_counts.sort.first # quot;Nejvetsi = prvniquot; -- [quot;Aquot;, {:count=>37, :word=>quot;Aquot;}] nepokojných snů, shle puts quot;Začínáme s quot; + nejpouzivanejsi[1][:word].to_s + quot;.quot; word_counts.sort.each do |word| proměnil v jakýsi nestv nejpouzivanejsi = word if word[1][:count] > nejpouzivanejsi[1][:count] end puts quot;Nejpoužívanější slovo je „quot; + nejpouzivanejsi[1][:word] + quot;“ s quot; + nejpouzivanejsi[1][:count].to_s + quot; výskyty.quot; Úvod do programování Přednáška 5
  • 8. seznam_nejpouzivanejsich_slov.rb text = File.read 'kafka_promena.txt' # ---> ... a co seznam slov podle frekvence pouziti? puts quot;Seznam nejpoužívanějších slov v Kafkově ‚Proměně‘:quot; most_frequent_words = word_counts.values.collect { |word| [word[:count], word [:word]] } most_frequent_words.sort.reverse.each_with_index do |word, i| puts quot;#{i+1}. #{word[1]}ttt(#{word[0]} výskytů)quot; end Když se Řehoř Samsa nepokojných snů, shle proměnil v jakýsi nestv Úvod do programování Přednáška 5
  • 9. nejpouzivanejsi_slovo.rb 1 text = File.read 'kafka_promena.txt' # ---> A ted neco trochu jineho... Najdeme nejpouzivanejsi slovo :) words = text.tr('-,();'quot;', '').split(' ') current_word = words.sort.first 2 word_counts = {} word_counts[current_word] = {} count = 0 words.sort.each do |word| if word == current_word count += 1 3 else count = 1 current_word = word end word_counts[word] = {:word => word, :count => count} Když se Řehoř Samsa end nejpouzivanejsi = word_counts.sort.first # quot;Nejvetsi = prvniquot; -- [quot;Aquot;, {:count=>37, :word=>quot;Aquot;}] nepokojných snů, shle puts quot;Začínáme s quot; + nejpouzivanejsi[1][:word].to_s + quot;.quot; word_counts.sort.each do |word| proměnil v jakýsi nestv nejpouzivanejsi = word if word[1][:count] > nejpouzivanejsi[1][:count] 4 end puts quot;Nejpoužívanější slovo je „quot; + nejpouzivanejsi[1][:word] + quot;“ s quot; + nejpouzivanejsi[1][:count].to_s + quot; výskyty.quot; Úvod do programování Přednáška 5
  • 10. „Křehký kód“ „Fragile code“ Úvod do programování Přednáška 5
  • 11. 2 Objektově orientované programování Úvod do programování
  • 12. 1. Nalít olej do pánve 2. Zapálit plyn 3. Vzít vejce 4. Rozklepnout vejce o okraj pánve Úvod do programování Přednáška 5
  • 13. 1. Nalít olej do pánve 2. Zapálit plyn 3. Vzít vejce, sůl a pepř 4. Rozklepnout vejce o okraj pánve Úvod do programování Přednáška 5
  • 14. „Udržovatelnost“ software Znovu-použití Re-usability Rozšiřitelnost Úvod do programování Přednáška 5
  • 15. Košík Produkty Objednávky Diskuse Platby Úvod do programování Přednáška 5
  • 16. Customer.php ~500 řádků kódu Košík Produkty Objednávky Diskuse Platby Úvod do programování Přednáška 5
  • 17. Customer.php ~500 řádků kódu Košík Produkty Objednávky Diskuse Platby Úvod do programování Přednáška 5
  • 18. ZÁKLADNÍ KONCEPTY OBJEKTOVĚ ORIENTOVANÉHO PROGRAMOVÁNÍ (OOP) 1. Zapouzdření Encapsulation 2. Modulárnost Modularity 3. Dědičnost Inheritance 4. Rozhraní Interface 5. Abstraktnost Abstraction 6. Polymorfie Polymorfism Úvod do programování Přednáška 5
  • 20. Zvíře Pes Ovce Úvod do programování Přednáška 5
  • 21. animals.rb 1 require 'pp' 2 3 # *** ANIMALS ***************************************************************** 4 5 #-- file Animal.rb 6 class Animal 7 8 attr_accessor :name, :position, :color 9 10 def initialize(name) 11 @name = name 12 @position = 0 13 @stuff_in_belly = 0 14 @walk_increment = 1 15 @run_increment = 10 16 puts quot;Hello, I am a #{self.class.to_s.downcase} named #{self.name}!quot; 17 end 18 19 def talk 20 puts quot;#{self.class}: ...quot; 21 22 end 23 Úvod do programování Přednáška 5
  • 22. animals.rb 24 def walk 25 @position += @walk_increment 26 end 27 28 def run 29 @position += @run_increment 30 end 31 32 def feed 33 @stuff_in_belly += 1 34 puts quot;[Chewing on some stuff and happy...]quot; 35 self.poop if @stuff_in_belly > 3 36 end 37 38 def hungry? 39 if @stuff_in_belly < 2 40 true 41 else 42 false 43 end 44 end 45 Úvod do programování Přednáška 5
  • 23. animals.rb 46 protected 47 48 def poop 49 puts quot;[Too much stuff in belly... pooping...]quot; 50 @stuff_in_belly = 0 51 end 52 53 end 54 55 Úvod do programování Přednáška 5
  • 24. animals.rb 56 #-- file Dog.rb 57 class Dog < Animal 58 59 def initialize(name, color) 60 super(name) 61 @color = color 62 @run_increment = 20 63 64 end 65 66 def talk 67 puts quot;#{self.name}: Woof! woof!quot; 68 end 69 70 def fetch(what='stick') 71 puts quot;[#{self.name} is fetching the #{what.downcase}...]quot; 72 end 73 74 end 75 76 Úvod do programování Přednáška 5
  • 25. animals.rb 77 #-- file Sheep.rb 78 class Sheep < Animal 79 80 def talk 81 puts quot;#{self.name}: Beeeeee!quot; 82 end 83 84 end 85 Úvod do programování Přednáška 5
  • 26. animals.rb 86 # === Dog ===================================================================== 87 88 # --- Create a dog 89 dog = Dog.new('Bitzer', 'yellow') 90 pp dog 91 92 # --- Dog's properties (attributes) 93 puts quot;Our dog's name is '#{dog.name}'.quot; 94 puts quot;And his color is #{dog.color}.quot; 95 Úvod do programování Přednáška 5
  • 27. animals.rb 96 # --- Make the dog do something 97 puts quot;> Talk, Bitzer!quot; 98 dog.talk 99 100 puts quot;> Fetch, Bitzer!quot; 101 dog.fetch 102 dog.fetch('Ball') 103 104 puts quot;> Walk, Bitzer!quot; 105 dog.walk 106 puts quot;Dog is at position: #{dog.position}.quot; 107 puts quot;> Run, Bitzer!quot; 108 dog.run 109 puts quot;Dog is at position: #{dog.position}.quot; 110 111 puts quot;> Have a snack, Bitzer!quot; 112 dog.feed 113 puts dog.hungry? 114 115 dog.feed 116 dog.feed 117 puts dog.hungry? 118 119 # dog.poop 120 dog.feed 121 122 Úvod do programování Přednáška 5
  • 28. animals.rb 123 puts quot;n---nnquot; 124 # === Sheep =================================================================== 125 126 sheep = Sheep.new('Shaun') 127 pp sheep 128 129 sheep.talk 130 131 puts sheep.position 132 sheep.run 133 puts sheep.position 134 135 # sheep.fetch Úvod do programování Přednáška 5
  • 29. http://ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html Úvod do programování Přednáška 5
  • 30. DOMÁCÍ ÚKOL Navrhněte a naprogramujte třídu TextAnalyzer TextAnalyzer: text • • characters • words • pages • unique_words • most_frequent_words • most_frequent_word Úvod do programování Přednáška 5
  • 31. Návrhové vzory Design patterns Úvod do programování Přednáška 5
  • 32. PŘÍKLAD Návrhový vzor ActiveRecord tabulka people ID Name Surname E-mail 1 John Smith smith@hotmail.com 2 Susanna Reddick susan@yahoo.com INSERT INTO people (name, surname, email) VALUES( 'John', 'Smith', 'smith@hotmail.com' ); SELECT * FROM people; SELECT * FROM people WHERE id = 1; SELECT * FROM people WHERE surname = 'Smith'; # ActiveRecord::Base.establish_connection .. Person.create(:name => 'John', :surname => 'Smith', :email => 'smith@hotmail.com') Person.find(:all) Person.find(1) Person.find_by_name('Smith') Úvod do programování Přednáška 5
  • 33. PŘÍKLAD Návrhový vzor ActiveRecord require 'rubygems' require_gem 'activerecord' require 'pp' ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => 'active_record_test.db') ActiveRecord::Base.connection.execute('CREATE TABLE quot;peoplequot; ( id INTEGER PRIMARY KEY NOT NULL, name VARCHAR (255), surname VARCHAR(255), email VARCHAR(255) )') class Person < ActiveRecord::Base end Person.create( :name => 'John', :surname => 'Smith', :email => 'smith@hotmail.com' ) Person.create( :name => 'Susanna', :surname => 'Reddick', :email => 'susan@hotmail.com' ) pp Person.find(:all) puts quot;nquot; pp Person.find(1) puts quot;nquot; pp Person.find_by_surname('Smith') puts quot;nquot; Úvod do programování Přednáška 5
  • 34. MODELOVÁNÍ Unified Modeling Language (UML) Úvod do programování Přednáška 5