SlideShare une entreprise Scribd logo
1  sur  26
Learn Ruby 2011
     Session 5
Our Sponsors
Flatsourcing, iSeatz, Koda, and Launchpad
Questions
Having any problems? Discover anything cool?
Looking for a Rescue
   Blocks, Iterators & Error Handling
Blocks

• Blocks are chunks of code between
  brackets ( {} ) or begin and end

• Blocks can be passed to methods like a
  parameter
• Blocks can also accept parameters
Blocks

ary = [“Tom”, “Dick”, “Harry”]
ary.each do |name|
  puts name
end

Tom
Dick
Harry
Blocks

ary = [“Tom”, “Dick”, “Harry”]
ary.each { |name| puts name }

Tom
Dick
Harry
Blocks
           class Array
             def iterate!
               self.each_with_index do |n, i|
                 self[i] = yield(n)
               end
             end
           end

           array = [1, 2, 3, 4]

           array.iterate! do |n|
             n ** 2
           end

           puts array.inspect

           # => [1, 4, 9, 16]


http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
Procs

• Procs are a special kind of block
• Procs are discreet Objects
• Procs set extra parameters to Nil
Procs
           class Array
             def iterate!(&code)
               self.each_with_index do |n, i|
                 self[i] = code.call(n)
               end
             end
           end

           array = [1, 2, 3, 4]

           array.iterate! do |n|
             n ** 2
           end

           puts array.inspect

           # => [1, 4, 9, 16]


http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
Procs
           class Array
             def iterate!(code)
               self.each_with_index do |n, i|
                 self[i] = code.call(n)
               end
             end
           end

           array = [1, 2, 3, 4]

           square = Proc.new do |n|
             n ** 2
           end

           array.iterate!(square)

           puts array.inspect

           # => [1, 4, 9, 16]



http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
Lambdas

• Lambdas are another special kind of block
• Unlike Procs, Lambdas check the number of
  arguments passed to them
• Lambdas behave more like methods
Lambdas

           def args(code)
             one, two = 1, 2
             code.call(one, two)
           end

           args(Proc.new{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}"})

           args(lambda{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}"})

           # => Give me a 1 and a 2 and a NilClass
           #*.rb:8: ArgumentError: wrong number of arguments (2 for 3) (ArgumentError)




http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
Lambdas
           def proc_return
             Proc.new { return "Proc.new"}.call
             return "proc_return method finished"
           end

           def lambda_return
             lambda { return "lambda" }.call
             return "lambda_return method finished"
           end

           puts proc_return
           puts lambda_return

           # => Proc.new
           # => lambda_return method finished


http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
Tell Me About Iterators
Exceptions

• An Exception is an error
• Exceptions are raised when something goes
  wrong
• You can create your own exceptions
Exceptions
def multiply(a, b)
  unless a.is_a?(Fixnum) && b.is_a?(Fixnum)
    raise “Arguments must be Fixnums!”
  end

  puts a * b
end

multiply 6, 2
multiply “F”, 2
multiple 4, true

12
Arguments must be Fixnums!
Arguments must be Fixnums!
Exceptions
def multiply(a, b)
  unless a.is_a?(Fixnum) && b.is_a?(Fixnum)
    raise ArgumentError
  end

  puts a * b
end

multiply 6, 2
multiply “F”, 2
multiple 4, true

12
ArgumentError: ArgumentError
ArgumentError: ArgumentError
Exceptions
def multiply(a, b)
  unless a.is_a?(Fixnum) && b.is_a?(Fixnum)
    raise ArgumentError, “must be Fixnums!”
  end

  puts a * b
end

multiply 6, 2
multiply “F”, 2
multiple 4, true

12
ArgumentError: must be Fixnums!
ArgumentError: must be Fixnums!
Begin...Rescue

• Ruby provides a mechanism for catching
  Exceptions and handling them gracefully.
• Ruby allows you to catch specific Exceptions
  or any Exception that might be raised
Begin...Rescue
def multiply(a, b)
  begin
    puts a * b
  rescue
    puts “Ooops!”
  end
end

multiply 6, 2
multiply “F”, 2
multiple 4, true

12
Ooops!
Ooops!
Begin...Rescue
def multiply(a, b)
  begin
    puts a * b
  rescue TypeError => e
    puts “Ooops! #{e.message}”
  end
end

multiply 6, 2
multiply “F”, 2
multiple 4, true

12
Ooops! String can't be coerced into Fixnum
Ooops! String can't be coerced into Fixnum
Reviewing

• Blocks
• Procs
• Lambdas
• Exceptions
• Begin...Rescue
For Next Week
For the New to Programming

•   Read Chapters 14 & 15 in LtP

•   Complete exercises for each chapter
For Everyone

•   Read Chapter 4, 8, 10 in PR1.9

•   Read more about blocks at http://www.robertsosinski.com/2008/12/21/
    understanding-ruby-blocks-procs-and-lambdas/


•   Work through Ruby Koans: about_blocks and
    about_iteration
Next Week


• Review
• The Ruby Community
Exercises

• Work on specific Ruby Koans:
 • ruby about_blocks.rb
 • ruby about_iteration.rb

Contenu connexe

Tendances

Tendances (13)

Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3Domain Specific Languages In Scala Duse3
Domain Specific Languages In Scala Duse3
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 
Ruby Presentation
Ruby Presentation Ruby Presentation
Ruby Presentation
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
Ruby Hell Yeah
Ruby Hell YeahRuby Hell Yeah
Ruby Hell Yeah
 
Ruby
RubyRuby
Ruby
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
ppt18
ppt18ppt18
ppt18
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt9
ppt9ppt9
ppt9
 

En vedette

Ril Annual Report 2007 08
Ril Annual Report 2007 08Ril Annual Report 2007 08
Ril Annual Report 2007 08Shambhu11
 
Standard ot sb presentation updated 20130402
Standard ot sb presentation updated 20130402Standard ot sb presentation updated 20130402
Standard ot sb presentation updated 20130402Gegeen Australia
 
Comarch For Vietnam Retail,Fmcg 2010 2012
Comarch For Vietnam Retail,Fmcg 2010  2012Comarch For Vietnam Retail,Fmcg 2010  2012
Comarch For Vietnam Retail,Fmcg 2010 2012Diep Nguyen
 
Eurasia In The Global Economy | Alan Greenhalgh
Eurasia In The Global Economy | Alan GreenhalghEurasia In The Global Economy | Alan Greenhalgh
Eurasia In The Global Economy | Alan GreenhalghShinesquad
 
Srategic triangulation past, present and possible
Srategic triangulation   past, present and possibleSrategic triangulation   past, present and possible
Srategic triangulation past, present and possibleSharon Johnson
 
Tru Coaching - For Men
Tru Coaching - For MenTru Coaching - For Men
Tru Coaching - For MenTru
 
5 UOW PhD Scholarship after coming Australia 25.11.12
5 UOW PhD Scholarship after coming Australia 25.11.125 UOW PhD Scholarship after coming Australia 25.11.12
5 UOW PhD Scholarship after coming Australia 25.11.12Gegeen Australia
 
6 els uec presentation_mongolia 2
6 els uec presentation_mongolia 26 els uec presentation_mongolia 2
6 els uec presentation_mongolia 2Gegeen Australia
 
Lift - Off International Film Festivals Sponsorship document
Lift - Off  International Film Festivals Sponsorship documentLift - Off  International Film Festivals Sponsorship document
Lift - Off International Film Festivals Sponsorship documentShinesquad
 
A systems approach to leading change
A systems approach to leading changeA systems approach to leading change
A systems approach to leading changeSharon Johnson
 
Slide set 4 some fundamentals of business
Slide set 4   some fundamentals of businessSlide set 4   some fundamentals of business
Slide set 4 some fundamentals of businessSharon Johnson
 
4 studyoverseasnewcomersankhtuyabelendalai25112012
4 studyoverseasnewcomersankhtuyabelendalai251120124 studyoverseasnewcomersankhtuyabelendalai25112012
4 studyoverseasnewcomersankhtuyabelendalai25112012Gegeen Australia
 
FAMILY TREE STRUCTURE
FAMILY TREE STRUCTUREFAMILY TREE STRUCTURE
FAMILY TREE STRUCTUREahLot
 

En vedette (20)

Ril Annual Report 2007 08
Ril Annual Report 2007 08Ril Annual Report 2007 08
Ril Annual Report 2007 08
 
Ojo.Html
Ojo.HtmlOjo.Html
Ojo.Html
 
Standard ot sb presentation updated 20130402
Standard ot sb presentation updated 20130402Standard ot sb presentation updated 20130402
Standard ot sb presentation updated 20130402
 
Creating powerful resumes
Creating powerful resumesCreating powerful resumes
Creating powerful resumes
 
Skills to win_in_interviews
Skills to win_in_interviewsSkills to win_in_interviews
Skills to win_in_interviews
 
Comarch For Vietnam Retail,Fmcg 2010 2012
Comarch For Vietnam Retail,Fmcg 2010  2012Comarch For Vietnam Retail,Fmcg 2010  2012
Comarch For Vietnam Retail,Fmcg 2010 2012
 
Eurasia In The Global Economy | Alan Greenhalgh
Eurasia In The Global Economy | Alan GreenhalghEurasia In The Global Economy | Alan Greenhalgh
Eurasia In The Global Economy | Alan Greenhalgh
 
Srategic triangulation past, present and possible
Srategic triangulation   past, present and possibleSrategic triangulation   past, present and possible
Srategic triangulation past, present and possible
 
1 MglausCom 25112012
1 MglausCom 251120121 MglausCom 25112012
1 MglausCom 25112012
 
Tru Coaching - For Men
Tru Coaching - For MenTru Coaching - For Men
Tru Coaching - For Men
 
5 UOW PhD Scholarship after coming Australia 25.11.12
5 UOW PhD Scholarship after coming Australia 25.11.125 UOW PhD Scholarship after coming Australia 25.11.12
5 UOW PhD Scholarship after coming Australia 25.11.12
 
6 els uec presentation_mongolia 2
6 els uec presentation_mongolia 26 els uec presentation_mongolia 2
6 els uec presentation_mongolia 2
 
Lift - Off International Film Festivals Sponsorship document
Lift - Off  International Film Festivals Sponsorship documentLift - Off  International Film Festivals Sponsorship document
Lift - Off International Film Festivals Sponsorship document
 
A systems approach to leading change
A systems approach to leading changeA systems approach to leading change
A systems approach to leading change
 
Slide set 4 some fundamentals of business
Slide set 4   some fundamentals of businessSlide set 4   some fundamentals of business
Slide set 4 some fundamentals of business
 
4 studyoverseasnewcomersankhtuyabelendalai25112012
4 studyoverseasnewcomersankhtuyabelendalai251120124 studyoverseasnewcomersankhtuyabelendalai25112012
4 studyoverseasnewcomersankhtuyabelendalai25112012
 
PART II.2 - Modern Physics
PART II.2 - Modern PhysicsPART II.2 - Modern Physics
PART II.2 - Modern Physics
 
Some ethical axes
Some ethical axesSome ethical axes
Some ethical axes
 
Ects 504, wr icebreaker
Ects 504, wr  icebreakerEcts 504, wr  icebreaker
Ects 504, wr icebreaker
 
FAMILY TREE STRUCTURE
FAMILY TREE STRUCTUREFAMILY TREE STRUCTURE
FAMILY TREE STRUCTURE
 

Similaire à Learn Ruby 2011 - Session 5 - Looking for a Rescue

Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1Pavel Tyk
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1Brady Cheng
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3mametter
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable LispAstrails
 
Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Apoorvi Kapoor
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9tomaspavelka
 

Similaire à Learn Ruby 2011 - Session 5 - Looking for a Rescue (20)

Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Ruby :: Training 1
Ruby :: Training 1Ruby :: Training 1
Ruby :: Training 1
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Ruby introduction part1
Ruby introduction part1Ruby introduction part1
Ruby introduction part1
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02Ruby19 osdc-090418222718-phpapp02
Ruby19 osdc-090418222718-phpapp02
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Ruby.new @ VilniusRB
Ruby.new @ VilniusRBRuby.new @ VilniusRB
Ruby.new @ VilniusRB
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9
 

Plus de James Thompson

Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018James Thompson
 
Bounded Contexts for Legacy Code
Bounded Contexts for Legacy CodeBounded Contexts for Legacy Code
Bounded Contexts for Legacy CodeJames Thompson
 
Beyond Accidental Arcitecture
Beyond Accidental ArcitectureBeyond Accidental Arcitecture
Beyond Accidental ArcitectureJames Thompson
 
Effective Pair Programming
Effective Pair ProgrammingEffective Pair Programming
Effective Pair ProgrammingJames Thompson
 
Wrapping an api with a ruby gem
Wrapping an api with a ruby gemWrapping an api with a ruby gem
Wrapping an api with a ruby gemJames Thompson
 
Microservices for the Monolith
Microservices for the MonolithMicroservices for the Monolith
Microservices for the MonolithJames Thompson
 
Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!James Thompson
 
Learn Ruby 2011 - Session 3
Learn Ruby 2011 - Session 3Learn Ruby 2011 - Session 3
Learn Ruby 2011 - Session 3James Thompson
 
Learn Ruby 2011 - Session 1
Learn Ruby 2011 - Session 1Learn Ruby 2011 - Session 1
Learn Ruby 2011 - Session 1James Thompson
 
Learn Ruby 2011 - Session 2
Learn Ruby 2011 - Session 2Learn Ruby 2011 - Session 2
Learn Ruby 2011 - Session 2James Thompson
 
Rails: Scaling Edition - Getting on Rails 3
Rails: Scaling Edition - Getting on Rails 3Rails: Scaling Edition - Getting on Rails 3
Rails: Scaling Edition - Getting on Rails 3James Thompson
 
Ruby For Web Development
Ruby For Web DevelopmentRuby For Web Development
Ruby For Web DevelopmentJames Thompson
 
Ruby Testing: Cucumber and RSpec
Ruby Testing: Cucumber and RSpecRuby Testing: Cucumber and RSpec
Ruby Testing: Cucumber and RSpecJames Thompson
 

Plus de James Thompson (14)

Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018Interfaces Not Required — RubyHACK 2018
Interfaces Not Required — RubyHACK 2018
 
Bounded Contexts for Legacy Code
Bounded Contexts for Legacy CodeBounded Contexts for Legacy Code
Bounded Contexts for Legacy Code
 
Beyond Accidental Arcitecture
Beyond Accidental ArcitectureBeyond Accidental Arcitecture
Beyond Accidental Arcitecture
 
Effective Pair Programming
Effective Pair ProgrammingEffective Pair Programming
Effective Pair Programming
 
Wrapping an api with a ruby gem
Wrapping an api with a ruby gemWrapping an api with a ruby gem
Wrapping an api with a ruby gem
 
Microservices for the Monolith
Microservices for the MonolithMicroservices for the Monolith
Microservices for the Monolith
 
Mocking & Stubbing
Mocking & StubbingMocking & Stubbing
Mocking & Stubbing
 
Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!Learn Ruby 2011 - Session 4 - Objects, Oh My!
Learn Ruby 2011 - Session 4 - Objects, Oh My!
 
Learn Ruby 2011 - Session 3
Learn Ruby 2011 - Session 3Learn Ruby 2011 - Session 3
Learn Ruby 2011 - Session 3
 
Learn Ruby 2011 - Session 1
Learn Ruby 2011 - Session 1Learn Ruby 2011 - Session 1
Learn Ruby 2011 - Session 1
 
Learn Ruby 2011 - Session 2
Learn Ruby 2011 - Session 2Learn Ruby 2011 - Session 2
Learn Ruby 2011 - Session 2
 
Rails: Scaling Edition - Getting on Rails 3
Rails: Scaling Edition - Getting on Rails 3Rails: Scaling Edition - Getting on Rails 3
Rails: Scaling Edition - Getting on Rails 3
 
Ruby For Web Development
Ruby For Web DevelopmentRuby For Web Development
Ruby For Web Development
 
Ruby Testing: Cucumber and RSpec
Ruby Testing: Cucumber and RSpecRuby Testing: Cucumber and RSpec
Ruby Testing: Cucumber and RSpec
 

Dernier

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.pdfUK Journal
 
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 2024Rafal Los
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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...Neo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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...Martijn de Jong
 
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...Miguel Araújo
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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.pdfChristopherTHyatt
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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 MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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 MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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 RobisonAnna Loughnan Colquhoun
 
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 2024The Digital Insurer
 

Dernier (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
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
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...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
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
 
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
 
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
 

Learn Ruby 2011 - Session 5 - Looking for a Rescue

  • 1. Learn Ruby 2011 Session 5
  • 3. Questions Having any problems? Discover anything cool?
  • 4. Looking for a Rescue Blocks, Iterators & Error Handling
  • 5. Blocks • Blocks are chunks of code between brackets ( {} ) or begin and end • Blocks can be passed to methods like a parameter • Blocks can also accept parameters
  • 6. Blocks ary = [“Tom”, “Dick”, “Harry”] ary.each do |name| puts name end Tom Dick Harry
  • 7. Blocks ary = [“Tom”, “Dick”, “Harry”] ary.each { |name| puts name } Tom Dick Harry
  • 8. Blocks class Array def iterate! self.each_with_index do |n, i| self[i] = yield(n) end end end array = [1, 2, 3, 4] array.iterate! do |n| n ** 2 end puts array.inspect # => [1, 4, 9, 16] http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
  • 9. Procs • Procs are a special kind of block • Procs are discreet Objects • Procs set extra parameters to Nil
  • 10. Procs class Array def iterate!(&code) self.each_with_index do |n, i| self[i] = code.call(n) end end end array = [1, 2, 3, 4] array.iterate! do |n| n ** 2 end puts array.inspect # => [1, 4, 9, 16] http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
  • 11. Procs class Array def iterate!(code) self.each_with_index do |n, i| self[i] = code.call(n) end end end array = [1, 2, 3, 4] square = Proc.new do |n| n ** 2 end array.iterate!(square) puts array.inspect # => [1, 4, 9, 16] http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
  • 12. Lambdas • Lambdas are another special kind of block • Unlike Procs, Lambdas check the number of arguments passed to them • Lambdas behave more like methods
  • 13. Lambdas def args(code) one, two = 1, 2 code.call(one, two) end args(Proc.new{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}"}) args(lambda{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}"}) # => Give me a 1 and a 2 and a NilClass #*.rb:8: ArgumentError: wrong number of arguments (2 for 3) (ArgumentError) http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
  • 14. Lambdas def proc_return Proc.new { return "Proc.new"}.call return "proc_return method finished" end def lambda_return lambda { return "lambda" }.call return "lambda_return method finished" end puts proc_return puts lambda_return # => Proc.new # => lambda_return method finished http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/
  • 15. Tell Me About Iterators
  • 16. Exceptions • An Exception is an error • Exceptions are raised when something goes wrong • You can create your own exceptions
  • 17. Exceptions def multiply(a, b) unless a.is_a?(Fixnum) && b.is_a?(Fixnum) raise “Arguments must be Fixnums!” end puts a * b end multiply 6, 2 multiply “F”, 2 multiple 4, true 12 Arguments must be Fixnums! Arguments must be Fixnums!
  • 18. Exceptions def multiply(a, b) unless a.is_a?(Fixnum) && b.is_a?(Fixnum) raise ArgumentError end puts a * b end multiply 6, 2 multiply “F”, 2 multiple 4, true 12 ArgumentError: ArgumentError ArgumentError: ArgumentError
  • 19. Exceptions def multiply(a, b) unless a.is_a?(Fixnum) && b.is_a?(Fixnum) raise ArgumentError, “must be Fixnums!” end puts a * b end multiply 6, 2 multiply “F”, 2 multiple 4, true 12 ArgumentError: must be Fixnums! ArgumentError: must be Fixnums!
  • 20. Begin...Rescue • Ruby provides a mechanism for catching Exceptions and handling them gracefully. • Ruby allows you to catch specific Exceptions or any Exception that might be raised
  • 21. Begin...Rescue def multiply(a, b) begin puts a * b rescue puts “Ooops!” end end multiply 6, 2 multiply “F”, 2 multiple 4, true 12 Ooops! Ooops!
  • 22. Begin...Rescue def multiply(a, b) begin puts a * b rescue TypeError => e puts “Ooops! #{e.message}” end end multiply 6, 2 multiply “F”, 2 multiple 4, true 12 Ooops! String can't be coerced into Fixnum Ooops! String can't be coerced into Fixnum
  • 23. Reviewing • Blocks • Procs • Lambdas • Exceptions • Begin...Rescue
  • 24. For Next Week For the New to Programming • Read Chapters 14 & 15 in LtP • Complete exercises for each chapter For Everyone • Read Chapter 4, 8, 10 in PR1.9 • Read more about blocks at http://www.robertsosinski.com/2008/12/21/ understanding-ruby-blocks-procs-and-lambdas/ • Work through Ruby Koans: about_blocks and about_iteration
  • 25. Next Week • Review • The Ruby Community
  • 26. Exercises • Work on specific Ruby Koans: • ruby about_blocks.rb • ruby about_iteration.rb

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n