SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Andere mochten auch

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
 

Andere mochten auch (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?
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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.pptxKatpro Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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 Nanonetsnaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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 interpreternaman860154
 

Kürzlich hochgeladen (20)

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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 

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

Hinweis der Redaktion

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