SlideShare a Scribd company logo
1 of 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

More Related Content

Viewers also liked

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
 

Viewers also liked (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?
 

Similar to 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
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 

Similar to 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
 
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
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 

Recently uploaded

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

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

Editor's Notes

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