SlideShare uma empresa Scribd logo
1 de 18
ENUMERABLE
A powerful Ruby Module for Collections
WHY USE ENUMERABLES

• Ruby's Enumerable module has methods for all kinds of tasks
  which operate on a collection.
• 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
ENUMERABLE METHODS

• Collection Behavior
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"]

Mais conteúdo relacionado

Semelhante a Enumerables

Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Coxlachie
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - IntroductionVagmi Mudumbai
 
Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into SwiftSarath C
 
Odoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new apiOdoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new apiOdoo
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails Hung Wu Lo
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
Workshop JavaScript ES6+
Workshop JavaScript ES6+Workshop JavaScript ES6+
Workshop JavaScript ES6+Roy Derks
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in RailsSeungkyun Nam
 

Semelhante a Enumerables (20)

Enumerables
EnumerablesEnumerables
Enumerables
 
Blocks by Lachs Cox
Blocks by Lachs CoxBlocks by Lachs Cox
Blocks by Lachs Cox
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
 
Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into Swift
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
Odoo from 7.0 to 8.0 API
Odoo from 7.0 to 8.0 APIOdoo from 7.0 to 8.0 API
Odoo from 7.0 to 8.0 API
 
Odoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new apiOdoo - From v7 to v8: the new api
Odoo - From v7 to v8: the new api
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Intro to ruby
Intro to rubyIntro to ruby
Intro to ruby
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Rest with-spray
Rest with-sprayRest with-spray
Rest with-spray
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Workshop JavaScript ES6+
Workshop JavaScript ES6+Workshop JavaScript ES6+
Workshop JavaScript ES6+
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in Rails
 

Mais de Blazing Cloud

Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyBlazing Cloud
 
Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3Blazing Cloud
 
Rails Class Intro - 1
Rails Class Intro - 1 Rails Class Intro - 1
Rails Class Intro - 1 Blazing Cloud
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2Blazing Cloud
 
RSpec Quick Reference
RSpec Quick ReferenceRSpec Quick Reference
RSpec Quick ReferenceBlazing Cloud
 
2day Ruby Class Intro
2day Ruby Class Intro2day Ruby Class Intro
2day Ruby Class IntroBlazing Cloud
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive GraphicsBlazing Cloud
 
Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3Blazing Cloud
 
Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)Blazing Cloud
 
What you don't know (yet)
What you don't know (yet)What you don't know (yet)
What you don't know (yet)Blazing Cloud
 
Introduction to Rails
Introduction to RailsIntroduction to Rails
Introduction to RailsBlazing Cloud
 
Ruby on Rails Class intro
Ruby on Rails Class introRuby on Rails Class intro
Ruby on Rails Class introBlazing Cloud
 
Ruby on rails toolbox
Ruby on rails toolboxRuby on rails toolbox
Ruby on rails toolboxBlazing Cloud
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentBlazing Cloud
 

Mais de Blazing Cloud (20)

Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_many
 
Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3
 
Rails Class Intro - 1
Rails Class Intro - 1 Rails Class Intro - 1
Rails Class Intro - 1
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2
 
RSpec Quick Reference
RSpec Quick ReferenceRSpec Quick Reference
RSpec Quick Reference
 
Extending rails
Extending railsExtending rails
Extending rails
 
2day Ruby Class Intro
2day Ruby Class Intro2day Ruby Class Intro
2day Ruby Class Intro
 
Mobile Lean UX
Mobile Lean UXMobile Lean UX
Mobile Lean UX
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
 
Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3
 
Form helpers
Form helpersForm helpers
Form helpers
 
Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)
 
What you don't know (yet)
What you don't know (yet)What you don't know (yet)
What you don't know (yet)
 
Introduction to Rails
Introduction to RailsIntroduction to Rails
Introduction to Rails
 
ActiveRecord
ActiveRecordActiveRecord
ActiveRecord
 
Ruby on Rails Class intro
Ruby on Rails Class introRuby on Rails Class intro
Ruby on Rails Class intro
 
Ruby on rails toolbox
Ruby on rails toolboxRuby on rails toolbox
Ruby on rails toolbox
 
Routes Controllers
Routes ControllersRoutes Controllers
Routes Controllers
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Active Record
Active RecordActive Record
Active Record
 

Último

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
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
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
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
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
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 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
 
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...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 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
 
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
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

Enumerables

  • 1. ENUMERABLE A powerful Ruby Module for Collections
  • 2. WHY USE ENUMERABLES • Ruby's Enumerable module has methods for all kinds of tasks which operate on a collection. • 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.
  • 3. 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
  • 4. MIXING IN ENUMERABLE class MyCollection include Enumerable #lots of code def each #more code end end
  • 5. VIEW ALL CLASSES MIXING IN ENUMERABLE ObjectSpace.each_object(Class) do |cl| puts cl if cl < Enumerable end
  • 7. 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
  • 9. 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
  • 10. 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"]
  • 11. GREP • The grep method 'searches' for members using a regular expression. >> v_names.grep /a/ => ["car"] >> v_names.grep(/a/) { |v| v.upcase} => ["CAR"]
  • 12. 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"
  • 13. 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
  • 14. 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
  • 15. WORKING WITH COMPLEX DATA irb >> load 'vehicles.rb' => true
  • 16. 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]
  • 17. 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"]
  • 18. 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"]