SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
Ruby
       A quick Ruby Tutorial
                                          •   Invented by Yukihiro Matsumoto, “Matz”
                                          •   1995
                                          •   Fully object-oriented
               COMP313
Source: Programming Ruby, The Pragmatic   •   alternative to Perl or Python
Programmers’ Guide by Dave Thomas, Chad
          Fowler, and Andy Hunt




                How to run                      Simple method example
 • Command line: ruby <file>              def sum (n1, n2)
                                            n1 + n2
 • Interactive: irb
                                          end

 • Resources:                             sum( 3 , 4) => 7
   – see web page                         sum(“cat”, “dog”) => “catdog”
   – man ruby
                                          load “fact.rb”
                                          fact(10) => 3628800




       executable shell script                         Method calls
 #!/usr/bin/ruby                          "gin joint".length   9
 print “hello worldn”                     "Rick".index("c")   2
                                          -1942.abs       1942
 or better: #!/usr/bin/env ruby
 make file executable: chmod +x file.rb   Strings: ‘asn’ => “asn”
                                          x=3
                                          y = “x is #{x}” => “x is 3”




                                                                                       1
Another method definition                         Name conventions/rules
def say_goodnight(name)                           • local var: start with lowercase or _
  "Good night, #{name}"                           • global var: start with $
end                                               • instance var: start with @
puts say_goodnight('Ma')                          • class var: start with @@
                                                  • class names, constant: start uppercase
                                                  following: any letter/digit/_ multiwords
produces: Good night, Ma                            either _ (instance) or mixed case
                                                    (class), methods may end in ?,!,=




          Naming examples                                  Arrays and Hashes
•   local: name, fish_and_chips, _26              • indexed collections, grow as needed
•   global: $debug, $_, $plan9                    • array: index/key is 0-based integer
                                                  • hash: index/key is any object
•   instance: @name, @point_1
                                                  a = [ 1, 2, “3”, “hello”]
•   class: @@total, @@SINGLE,
                                                  a[0] => 1                      a[2] => “3”
•   constant/class: PI, MyClass,                  a[5] => nil (ala null in Java, but proper Object)
    FeetPerMile
                                                  a[6] = 1
                                                  a => [1, 2, “3”, “hello”, nil, nil, 1]




            Hash examples                                  Control: if example
inst = { “a” => 1, “b” => 2 }                     if count > 10
inst[“a”] => 1                                      puts "Try again"
inst[“c”] => nil
                                                  elsif tries == 3
inst = Hash.new(0) #explicit new with default 0
  instead of nil for empty slots                    puts "You lose"
inst[“a”] => 0                                    else
inst[“a”] += 1                                      puts "Enter a number"
inst[“a”] => 1                                    end




                                                                                                      2
Control: while example                                                 nil is treated as false
while weight < 100 and num_pallets <= 30                            while line = gets
 pallet = next_pallet()                                              puts line.downcase
 weight += pallet.weight                                            end
 num_pallets += 1
end




                                                                         builtin support for Regular
            Statement modifiers
                                                                                 expressions
 • useful for single statement if or while                          /Perl|Python/ matches Perl or Python
 • similar to Perl                                                  /ab*c/ matches one a, zero or more bs and
                                                                       one c
 • statement followed by condition:
                                                                    /ab+c/ matches one a, one or more bs and one
                                                                       c
 puts "Danger" if radiation > 3000                                  /s/ matches any white space
                                                                    /d/ matches any digit
 square = 2                                                         /w/ characters in typical words
 square = square*square while square < 1000                         /./ any character
                                                                    (more later)




                more on regexps                                               Code blocks and yield
 if line =~ /Perl|Python/                                           def call_block
   puts "Scripting language mentioned: #{line}"                      puts "Start of method"
 end                                                                 yield
                                                                     yield
                                                                     puts "End of method"
 line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby'
                                                                    end
 line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby’

                                                                    call_block { puts "In the block" }   produces:
 # replace all occurances of both ‘Perl’ and ‘Python’ with ‘Ruby’   Start of method
 line.gsub(/Perl|Python/, 'Ruby')                                   In the block
                                                                    In the block
                                                                    End of method




                                                                                                                     3
parameters for yield                           Code blocks for iteration
def call_block                                    animals = %w( ant bee cat dog elk ) # create an array
 yield("hello",2)                                  # shortcut for animals = {“ant”,”bee”,”cat”,”dog”,”elk”}
end                                               animals.each {|animal| puts animal } # iterate
                                                           produces:
then                                              ant
                                                  bee
                                                  cat
call_block { | s, n | puts s*n, "n" }   prints
                                                  dog
hellohello
                                                  elk




 Implement “each” with “yield”                                   More iterations
# within class Array...                           [ 'cat', 'dog', 'horse' ].each {|name| print name, "
                                                     "}
def each
                                                  5.times { print "*" }
 for every element # <-- not valid Ruby
                                                  3.upto(6) {|i| print i }
  yield(element)                                  ('a'..'e').each {|char| print char }
 end                                              [1,2,3].find { |x| x > 1}
end                                               (1...10).find_all { |x| x < 3}




                        I/O                       leaving the Perl legacy behind
• puts and print, and C-like printf:              while gets
printf("Number: %5.2f,nString: %sn", 1.23,       if /Ruby/
   "hello")                                          print
 #produces:                                        end
Number: 1.23,                                     end
String: hello
#input                                            ARGF.each {|line| print line if line =~ /Ruby/ }
line = gets
print line                                        print ARGF.grep(/Ruby/)




                                                                                                              4
Classes                                    override to_s
class Song                                        s.to_s => "#<Song:0x2282d0>"
 def initialize(name, artist, duration)
  @name = name                                    class Song
  @artist = artist                                 def to_s
  @duration = duration                               "Song: #@name--#@artist (#@duration)"
 end                                               end
end                                               end

song = Song.new("Bicylops", "Fleck", 260)         s.to_s => "Song: Bicylops--Fleck (260 )”




                 Some subclass                           supply to_s for subclass
class KaraokeSong < Song                          class KaraokeSong < Song
                                                   # Format as a string by appending lyrics to parent's to_s value.
 def initialize(name, artist, duration, lyrics)
                                                   def to_s
   super(name, artist, duration)                    super + " [#@lyrics]"
   @lyrics = lyrics                                end
 end                                              end

end                                               song.to_s    "Song: My Way--Sinatra (225) [And now, the...]"
song = KaraokeSong.new("My Way", "Sinatra",
  225, "And now, the...")
song.to_s       "Song: My Way--Sinatra (225)"




                       Accessors
class Song
 def name
   @name
 end
end
s.name => “My Way”

# simpler way to achieve the same
class Song
 attr_reader :name, :artist, :duration
end




                                                                                                                      5

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
Go &lt;-> Ruby
Go &lt;-> RubyGo &lt;-> Ruby
Go &lt;-> Ruby
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartCon
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Operator Overloading In Scala
Operator Overloading In ScalaOperator Overloading In Scala
Operator Overloading In Scala
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Object Equality in Scala
Object Equality in ScalaObject Equality in Scala
Object Equality in Scala
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
 

Andere mochten auch

中国移动Boss3.0技术方案
中国移动Boss3.0技术方案中国移动Boss3.0技术方案
中国移动Boss3.0技术方案
yiditushe
 
Hypocrite Dr. Shriniwas Kashalikar
Hypocrite Dr. Shriniwas KashalikarHypocrite Dr. Shriniwas Kashalikar
Hypocrite Dr. Shriniwas Kashalikar
drsolapurkar
 
Christmas in Germany
Christmas in GermanyChristmas in Germany
Christmas in Germany
Sayali Dhoke
 
S T U D Y O F G I T A 4 T H F L O W E R D R
S T U D Y  O F  G I T A 4 T H  F L O W E R  D RS T U D Y  O F  G I T A 4 T H  F L O W E R  D R
S T U D Y O F G I T A 4 T H F L O W E R D R
drsolapurkar
 
由一个简单的程序谈起--之四
由一个简单的程序谈起--之四由一个简单的程序谈起--之四
由一个简单的程序谈起--之四
yiditushe
 
W A L K I N G T O W E L L N E S S H O L I S T I C V I E W D R S H R I N...
W A L K I N G  T O  W E L L N E S S  H O L I S T I C  V I E W  D R  S H R I N...W A L K I N G  T O  W E L L N E S S  H O L I S T I C  V I E W  D R  S H R I N...
W A L K I N G T O W E L L N E S S H O L I S T I C V I E W D R S H R I N...
drsolapurkar
 

Andere mochten auch (20)

11 19 Biogas
11 19 Biogas11 19 Biogas
11 19 Biogas
 
Done For You SEO SMO PowerPoint
Done For You SEO SMO PowerPoint   Done For You SEO SMO PowerPoint
Done For You SEO SMO PowerPoint
 
Not So Native
Not So NativeNot So Native
Not So Native
 
Plan for Physical Activity, Sport and Health in Catalonia
Plan for Physical Activity, Sport and Health in CataloniaPlan for Physical Activity, Sport and Health in Catalonia
Plan for Physical Activity, Sport and Health in Catalonia
 
Mecanismo
MecanismoMecanismo
Mecanismo
 
Avaliação da formação contínua
Avaliação da formação contínuaAvaliação da formação contínua
Avaliação da formação contínua
 
中国移动Boss3.0技术方案
中国移动Boss3.0技术方案中国移动Boss3.0技术方案
中国移动Boss3.0技术方案
 
Hypocrite Dr. Shriniwas Kashalikar
Hypocrite Dr. Shriniwas KashalikarHypocrite Dr. Shriniwas Kashalikar
Hypocrite Dr. Shriniwas Kashalikar
 
Christmas in Germany
Christmas in GermanyChristmas in Germany
Christmas in Germany
 
cgipmtut
cgipmtutcgipmtut
cgipmtut
 
Rf matematicas i
Rf matematicas iRf matematicas i
Rf matematicas i
 
Some shoe trends ´07
Some shoe trends ´07Some shoe trends ´07
Some shoe trends ´07
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Australia
AustraliaAustralia
Australia
 
Wapflow
WapflowWapflow
Wapflow
 
Che cosa è l'amore?
Che cosa è l'amore?Che cosa è l'amore?
Che cosa è l'amore?
 
Winter09TECH
Winter09TECHWinter09TECH
Winter09TECH
 
S T U D Y O F G I T A 4 T H F L O W E R D R
S T U D Y  O F  G I T A 4 T H  F L O W E R  D RS T U D Y  O F  G I T A 4 T H  F L O W E R  D R
S T U D Y O F G I T A 4 T H F L O W E R D R
 
由一个简单的程序谈起--之四
由一个简单的程序谈起--之四由一个简单的程序谈起--之四
由一个简单的程序谈起--之四
 
W A L K I N G T O W E L L N E S S H O L I S T I C V I E W D R S H R I N...
W A L K I N G  T O  W E L L N E S S  H O L I S T I C  V I E W  D R  S H R I N...W A L K I N G  T O  W E L L N E S S  H O L I S T I C  V I E W  D R  S H R I N...
W A L K I N G T O W E L L N E S S H O L I S T I C V I E W D R S H R I N...
 

Ähnlich wie ruby1_6up

Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
ppparthpatel123
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
Brady Cheng
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Sway Wang
 

Ähnlich wie ruby1_6up (20)

Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Introducing Ruby
Introducing RubyIntroducing Ruby
Introducing Ruby
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a Rescue
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Mehr von tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 

Mehr von tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

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
 
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
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

ruby1_6up

  • 1. Ruby A quick Ruby Tutorial • Invented by Yukihiro Matsumoto, “Matz” • 1995 • Fully object-oriented COMP313 Source: Programming Ruby, The Pragmatic • alternative to Perl or Python Programmers’ Guide by Dave Thomas, Chad Fowler, and Andy Hunt How to run Simple method example • Command line: ruby <file> def sum (n1, n2) n1 + n2 • Interactive: irb end • Resources: sum( 3 , 4) => 7 – see web page sum(“cat”, “dog”) => “catdog” – man ruby load “fact.rb” fact(10) => 3628800 executable shell script Method calls #!/usr/bin/ruby "gin joint".length 9 print “hello worldn” "Rick".index("c") 2 -1942.abs 1942 or better: #!/usr/bin/env ruby make file executable: chmod +x file.rb Strings: ‘asn’ => “asn” x=3 y = “x is #{x}” => “x is 3” 1
  • 2. Another method definition Name conventions/rules def say_goodnight(name) • local var: start with lowercase or _ "Good night, #{name}" • global var: start with $ end • instance var: start with @ puts say_goodnight('Ma') • class var: start with @@ • class names, constant: start uppercase following: any letter/digit/_ multiwords produces: Good night, Ma either _ (instance) or mixed case (class), methods may end in ?,!,= Naming examples Arrays and Hashes • local: name, fish_and_chips, _26 • indexed collections, grow as needed • global: $debug, $_, $plan9 • array: index/key is 0-based integer • hash: index/key is any object • instance: @name, @point_1 a = [ 1, 2, “3”, “hello”] • class: @@total, @@SINGLE, a[0] => 1 a[2] => “3” • constant/class: PI, MyClass, a[5] => nil (ala null in Java, but proper Object) FeetPerMile a[6] = 1 a => [1, 2, “3”, “hello”, nil, nil, 1] Hash examples Control: if example inst = { “a” => 1, “b” => 2 } if count > 10 inst[“a”] => 1 puts "Try again" inst[“c”] => nil elsif tries == 3 inst = Hash.new(0) #explicit new with default 0 instead of nil for empty slots puts "You lose" inst[“a”] => 0 else inst[“a”] += 1 puts "Enter a number" inst[“a”] => 1 end 2
  • 3. Control: while example nil is treated as false while weight < 100 and num_pallets <= 30 while line = gets pallet = next_pallet() puts line.downcase weight += pallet.weight end num_pallets += 1 end builtin support for Regular Statement modifiers expressions • useful for single statement if or while /Perl|Python/ matches Perl or Python • similar to Perl /ab*c/ matches one a, zero or more bs and one c • statement followed by condition: /ab+c/ matches one a, one or more bs and one c puts "Danger" if radiation > 3000 /s/ matches any white space /d/ matches any digit square = 2 /w/ characters in typical words square = square*square while square < 1000 /./ any character (more later) more on regexps Code blocks and yield if line =~ /Perl|Python/ def call_block puts "Scripting language mentioned: #{line}" puts "Start of method" end yield yield puts "End of method" line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby' end line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby’ call_block { puts "In the block" } produces: # replace all occurances of both ‘Perl’ and ‘Python’ with ‘Ruby’ Start of method line.gsub(/Perl|Python/, 'Ruby') In the block In the block End of method 3
  • 4. parameters for yield Code blocks for iteration def call_block animals = %w( ant bee cat dog elk ) # create an array yield("hello",2) # shortcut for animals = {“ant”,”bee”,”cat”,”dog”,”elk”} end animals.each {|animal| puts animal } # iterate produces: then ant bee cat call_block { | s, n | puts s*n, "n" } prints dog hellohello elk Implement “each” with “yield” More iterations # within class Array... [ 'cat', 'dog', 'horse' ].each {|name| print name, " "} def each 5.times { print "*" } for every element # <-- not valid Ruby 3.upto(6) {|i| print i } yield(element) ('a'..'e').each {|char| print char } end [1,2,3].find { |x| x > 1} end (1...10).find_all { |x| x < 3} I/O leaving the Perl legacy behind • puts and print, and C-like printf: while gets printf("Number: %5.2f,nString: %sn", 1.23, if /Ruby/ "hello") print #produces: end Number: 1.23, end String: hello #input ARGF.each {|line| print line if line =~ /Ruby/ } line = gets print line print ARGF.grep(/Ruby/) 4
  • 5. Classes override to_s class Song s.to_s => "#<Song:0x2282d0>" def initialize(name, artist, duration) @name = name class Song @artist = artist def to_s @duration = duration "Song: #@name--#@artist (#@duration)" end end end end song = Song.new("Bicylops", "Fleck", 260) s.to_s => "Song: Bicylops--Fleck (260 )” Some subclass supply to_s for subclass class KaraokeSong < Song class KaraokeSong < Song # Format as a string by appending lyrics to parent's to_s value. def initialize(name, artist, duration, lyrics) def to_s super(name, artist, duration) super + " [#@lyrics]" @lyrics = lyrics end end end end song.to_s "Song: My Way--Sinatra (225) [And now, the...]" song = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...") song.to_s "Song: My Way--Sinatra (225)" Accessors class Song def name @name end end s.name => “My Way” # simpler way to achieve the same class Song attr_reader :name, :artist, :duration end 5