SlideShare uma empresa Scribd logo
1 de 5
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
 

Último (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
[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
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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?
 
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
 
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...
 

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