SlideShare une entreprise Scribd logo
1  sur  35
Class 4 Regular Expressions & Enumerables
Regular Expressions /regex will find me/
What are Regular Expressions Regular expressions allow matching and manipulation of textual data. Abbreviated as regex or regexp, or alternatively, just patterns
What are Regular Expressions For?	 Scan a string for multiple occurrences of a pattern. Replace part of a string with another string. Split a string based on a matching separator.
Regular Expressions in Ruby ,[object Object]
 They are escaped with a backward slash (.,[object Object]
Regex Basics [abc] A single character: a, b or c  [^abc] Any single character but a, b, or c  [a-z] Any single character in the range a-z  [a-zA-Z] Any single character in the range a-z or A-Z  ^ Start of line  $ End of line   Start of string   End of string
Regex Basics cont... . Any single character   Any whitespace character   Any non-whitespace character   Any digit   Any non-digit   Any word character (letter, number, underscore)   Any non-word character   Any word boundary character
Regex Basics cont... (...) Capture everything enclosed  (a|b) a or b  a? Zero or one of a  a* Zero or more of a  a+ One or more of a  a{3} Exactly 3 of a  a{3,} 3 or more of a   a{3,6} Between 3 and 6 of a
Regex:  .match >> category = "power tools" => "power tools" >> puts "on Sale" if category.match(/power tools/) on Sale >> puts "on Sale" if /power tools/.match(category) on Sale
Regex:  =~ >> category = "shoes" => "shoes" >> puts "15 % off" if category =~ /shoes/ 15 % off >> puts "15 % off" if /shoes/ =~ category 15 % off >> /pants/ =~ category => nil >> /shoes/ =~ category => 0 >> category = "women's shoes” >> /shoes/ =~ category => 8 8th character
Scan >> numbers = "one two three" => "one two three" >> numbers.scan(/+/) => ["one", "two", "three”]
Split with Regular Expressions >> "one twothree".split(//) => ["one", ”two", "three"]
gsub ”fred,mary,john".gsub(/fred/, “XXX”) => “XXX,mary,john”
gsub with a block "one twothree".gsub(/(+)/) do |w| 	puts w end one two three
Title Case Capitalize All Words of a Sentence: >> full_name.gsub(//){|s| s.upcase} => "Yukihiro Matsumoto"
Live Coding Example Scraping Thentic.com
Enumerables Collection Behavior
Why Use Enumerables Ruby's Enumerable module has methods for all kinds of tasks.  If you can imagine a use for the #each method other than simply iterating, there is a good chance a method exists to do what you have in mind.
What does Enumerable Mean? Collection objects (instances of Array, Hash, etc) typically “mixin” the Enumerable module The Enumerable module gives objects of collection classes additional collection-specific behaviors. The class requiring the Enumerable module must have an #each method because the additional collection-specific behaviors given by Enumerable are defined in terms of #each
Mixing in Enumerable class MyCollection 	include Enumerable 	#lots of code 	def each 		#more code 	end end
View all Classes Mixing in Enumerable ObjectSpace.each_object(Class) do |cl|  		puts cl if cl < Enumerable end
Enumerable::Enumerator Struct::Tms Dir File IO Range Struct Hash Array String Struct::Group Struct::Passwd MyCollection StringIO Gem::SourceIndex YAML::Set YAML::Pairs YAML::Omap YAML::SpecialHas
Test an Instance or Class  >> a = [1,2,3] => [1, 2, 3] >> a.respond_to? :any? => true >> a.is_a? Enumerable => true >> Array < Enumerable => true
each Classes that include the Enumerable module must have an #each method.  The #each method yields items to a supplied code block, one at a time Different Classes define #each differently Array: #each yields each element Hash: each yields #each key/value pair as a two-element array >> v_names = %w(car truck bike) => ["car", "truck", "bike"] >> v_names.each do |vehicle| ?> puts vehicle >> end
map The map method modifies each member according to instructions in a block and returns the modified collection of members. >> v_names.map { |v| v.upcase} => ["CAR", "TRUCK", "BIKE"]
grep The grep method 'searches' for members using a regular expression.  >> v_names.grep /a/ => ["car"] >> v_names.grep(/a/) { |v| v.upcase} => ["CAR"]
find >> v_names.find { |v| v.size > 3} => "truck" >> v_names.find { |v| v.size > 2} => "car" >> v_names.find do |v|  v.size > 3 && v.size < 5 end => "bike"
all? The all? method returns true if all of the members of a collection satisfy the evaluation of the block.  Otherwise it returns false. >> v_names.all? { |v| v.length > 2} => true >> v_names.all? { |v| v.length > 10} => false
any? The any? method returns true if any of the members of a collection satisfy the evaluation of the block.  Otherwise it returns false. >> v_names.any? { |v| v.length == 3} => true >> v_names.any? { |v| v = "car"} => true
Working with Complex Data irb >> load 'vehicles.rb' => true
inject >> $vehicles.inject(0) do |total_wheels, v| ?> total_wheels += v[:wheels] >> end => 10 >> $vehicles.inject([]) do |classes, v| ?> classes += v[:classes] >> end.uniq => [:ground, :water, :air]
Complex Operations >> $vehicles.find do |v| ?> v[:name] =~ /Plane/ >> end[:name] => "Plane" >> $vehicles.find_all do |v| ?> v[:name] =~ /Plane/ >> end.collect { |v| v[:name] } => ["Plane", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:wheels] > 0  >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike"]
Complex Operations Continued >> $vehicles.find_all do |v| ?> v[:classes].include? :ground >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:classes].include? :air >> end.collect { |v| v[:name] } => ["Plane", "Helicopter", "Sea Plane"]
Homework Chapters: 10.1 – 10.8 11.1 -11.8

Contenu connexe

En vedette

2014 09 30_t1_bioinformatics_wim_vancriekinge
2014 09 30_t1_bioinformatics_wim_vancriekinge2014 09 30_t1_bioinformatics_wim_vancriekinge
2014 09 30_t1_bioinformatics_wim_vancriekingeProf. Wim Van Criekinge
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Prof. Wim Van Criekinge
 
3 Strings Symbols
3 Strings Symbols3 Strings Symbols
3 Strings Symbolsliahhansen
 
6 Modules Inheritance Gems
6 Modules Inheritance Gems6 Modules Inheritance Gems
6 Modules Inheritance Gemsliahhansen
 
2 Slides Conditionals Iterators Blocks Hashes Arrays
2 Slides   Conditionals Iterators Blocks Hashes Arrays2 Slides   Conditionals Iterators Blocks Hashes Arrays
2 Slides Conditionals Iterators Blocks Hashes Arraysliahhansen
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 

En vedette (11)

2014 09 30_t1_bioinformatics_wim_vancriekinge
2014 09 30_t1_bioinformatics_wim_vancriekinge2014 09 30_t1_bioinformatics_wim_vancriekinge
2014 09 30_t1_bioinformatics_wim_vancriekinge
 
Web Scraping
Web ScrapingWeb Scraping
Web Scraping
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
1 Intro
1   Intro1   Intro
1 Intro
 
3 Strings Symbols
3 Strings Symbols3 Strings Symbols
3 Strings Symbols
 
6 Modules Inheritance Gems
6 Modules Inheritance Gems6 Modules Inheritance Gems
6 Modules Inheritance Gems
 
2 Slides Conditionals Iterators Blocks Hashes Arrays
2 Slides   Conditionals Iterators Blocks Hashes Arrays2 Slides   Conditionals Iterators Blocks Hashes Arrays
2 Slides Conditionals Iterators Blocks Hashes Arrays
 
5 Files Io
5 Files Io5 Files Io
5 Files Io
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 

Similaire à 4 Regex Enumerables

PERL Unit 6 regular expression
PERL Unit 6 regular expressionPERL Unit 6 regular expression
PERL Unit 6 regular expressionBinsent Ribera
 
We9 Struts 2.0
We9 Struts 2.0We9 Struts 2.0
We9 Struts 2.0wangjiaz
 
Freebasing for Fun and Enhancement
Freebasing for Fun and EnhancementFreebasing for Fun and Enhancement
Freebasing for Fun and EnhancementMrDys
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operatorsmussawir20
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And PortKeiichi Daiba
 
Erlang with Regexp Perl And Port
Erlang with Regexp Perl And PortErlang with Regexp Perl And Port
Erlang with Regexp Perl And PortKeiichi Daiba
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented PerlBunty Ray
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 

Similaire à 4 Regex Enumerables (20)

Ruby RegEx
Ruby RegExRuby RegEx
Ruby RegEx
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
PERL Unit 6 regular expression
PERL Unit 6 regular expressionPERL Unit 6 regular expression
PERL Unit 6 regular expression
 
Php2
Php2Php2
Php2
 
Prototype js
Prototype jsPrototype js
Prototype js
 
Form Validation
Form ValidationForm Validation
Form Validation
 
Ruby Enumerable
Ruby EnumerableRuby Enumerable
Ruby Enumerable
 
We9 Struts 2.0
We9 Struts 2.0We9 Struts 2.0
We9 Struts 2.0
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 
Changing Template Engine
Changing Template EngineChanging Template Engine
Changing Template Engine
 
Freebasing for Fun and Enhancement
Freebasing for Fun and EnhancementFreebasing for Fun and Enhancement
Freebasing for Fun and Enhancement
 
Combres
CombresCombres
Combres
 
XSD
XSDXSD
XSD
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
 
Array
ArrayArray
Array
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port
 
Erlang with Regexp Perl And Port
Erlang with Regexp Perl And PortErlang with Regexp Perl And Port
Erlang with Regexp Perl And Port
 
CGI With Object Oriented Perl
CGI With Object Oriented PerlCGI With Object Oriented Perl
CGI With Object Oriented Perl
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 

Dernier (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

4 Regex Enumerables

  • 1. Class 4 Regular Expressions & Enumerables
  • 3. What are Regular Expressions Regular expressions allow matching and manipulation of textual data. Abbreviated as regex or regexp, or alternatively, just patterns
  • 4. What are Regular Expressions For? Scan a string for multiple occurrences of a pattern. Replace part of a string with another string. Split a string based on a matching separator.
  • 5.
  • 6.
  • 7. Regex Basics [abc] A single character: a, b or c [^abc] Any single character but a, b, or c [a-z] Any single character in the range a-z [a-zA-Z] Any single character in the range a-z or A-Z ^ Start of line $ End of line Start of string End of string
  • 8. Regex Basics cont... . Any single character Any whitespace character Any non-whitespace character Any digit Any non-digit Any word character (letter, number, underscore) Any non-word character Any word boundary character
  • 9. Regex Basics cont... (...) Capture everything enclosed (a|b) a or b a? Zero or one of a a* Zero or more of a a+ One or more of a a{3} Exactly 3 of a a{3,} 3 or more of a a{3,6} Between 3 and 6 of a
  • 10. Regex: .match >> category = "power tools" => "power tools" >> puts "on Sale" if category.match(/power tools/) on Sale >> puts "on Sale" if /power tools/.match(category) on Sale
  • 11. Regex: =~ >> category = "shoes" => "shoes" >> puts "15 % off" if category =~ /shoes/ 15 % off >> puts "15 % off" if /shoes/ =~ category 15 % off >> /pants/ =~ category => nil >> /shoes/ =~ category => 0 >> category = "women's shoes” >> /shoes/ =~ category => 8 8th character
  • 12. Scan >> numbers = "one two three" => "one two three" >> numbers.scan(/+/) => ["one", "two", "three”]
  • 13. Split with Regular Expressions >> "one twothree".split(//) => ["one", ”two", "three"]
  • 15. gsub with a block "one twothree".gsub(/(+)/) do |w| puts w end one two three
  • 16. Title Case Capitalize All Words of a Sentence: >> full_name.gsub(//){|s| s.upcase} => "Yukihiro Matsumoto"
  • 17. Live Coding Example Scraping Thentic.com
  • 19. Why Use Enumerables Ruby's Enumerable module has methods for all kinds of tasks. If you can imagine a use for the #each method other than simply iterating, there is a good chance a method exists to do what you have in mind.
  • 20. What does Enumerable Mean? Collection objects (instances of Array, Hash, etc) typically “mixin” the Enumerable module The Enumerable module gives objects of collection classes additional collection-specific behaviors. The class requiring the Enumerable module must have an #each method because the additional collection-specific behaviors given by Enumerable are defined in terms of #each
  • 21. Mixing in Enumerable class MyCollection include Enumerable #lots of code def each #more code end end
  • 22. View all Classes Mixing in Enumerable ObjectSpace.each_object(Class) do |cl| puts cl if cl < Enumerable end
  • 23. Enumerable::Enumerator Struct::Tms Dir File IO Range Struct Hash Array String Struct::Group Struct::Passwd MyCollection StringIO Gem::SourceIndex YAML::Set YAML::Pairs YAML::Omap YAML::SpecialHas
  • 24. Test an Instance or Class >> a = [1,2,3] => [1, 2, 3] >> a.respond_to? :any? => true >> a.is_a? Enumerable => true >> Array < Enumerable => true
  • 25. each Classes that include the Enumerable module must have an #each method. The #each method yields items to a supplied code block, one at a time Different Classes define #each differently Array: #each yields each element Hash: each yields #each key/value pair as a two-element array >> v_names = %w(car truck bike) => ["car", "truck", "bike"] >> v_names.each do |vehicle| ?> puts vehicle >> end
  • 26. map The map method modifies each member according to instructions in a block and returns the modified collection of members. >> v_names.map { |v| v.upcase} => ["CAR", "TRUCK", "BIKE"]
  • 27. grep The grep method 'searches' for members using a regular expression. >> v_names.grep /a/ => ["car"] >> v_names.grep(/a/) { |v| v.upcase} => ["CAR"]
  • 28. find >> v_names.find { |v| v.size > 3} => "truck" >> v_names.find { |v| v.size > 2} => "car" >> v_names.find do |v| v.size > 3 && v.size < 5 end => "bike"
  • 29. all? The all? method returns true if all of the members of a collection satisfy the evaluation of the block. Otherwise it returns false. >> v_names.all? { |v| v.length > 2} => true >> v_names.all? { |v| v.length > 10} => false
  • 30. any? The any? method returns true if any of the members of a collection satisfy the evaluation of the block. Otherwise it returns false. >> v_names.any? { |v| v.length == 3} => true >> v_names.any? { |v| v = "car"} => true
  • 31. Working with Complex Data irb >> load 'vehicles.rb' => true
  • 32. inject >> $vehicles.inject(0) do |total_wheels, v| ?> total_wheels += v[:wheels] >> end => 10 >> $vehicles.inject([]) do |classes, v| ?> classes += v[:classes] >> end.uniq => [:ground, :water, :air]
  • 33. Complex Operations >> $vehicles.find do |v| ?> v[:name] =~ /Plane/ >> end[:name] => "Plane" >> $vehicles.find_all do |v| ?> v[:name] =~ /Plane/ >> end.collect { |v| v[:name] } => ["Plane", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:wheels] > 0 >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike"]
  • 34. Complex Operations Continued >> $vehicles.find_all do |v| ?> v[:classes].include? :ground >> end.collect { |v| v[:name] } => ["Car", "Truck", "Bike", "Sea Plane"] >> $vehicles.find_all do |v| ?> v[:classes].include? :air >> end.collect { |v| v[:name] } => ["Plane", "Helicopter", "Sea Plane"]
  • 35. Homework Chapters: 10.1 – 10.8 11.1 -11.8

Notes de l'éditeur

  1. s finds spaces, tabs and new lines
  2. its fine to use is_a in irb..in code should use respond_to?