SlideShare ist ein Scribd-Unternehmen logo
1 von 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-speciïŹc behaviors.
‱ The class requiring the Enumerable module must have an #each
  method because the additional collection-speciïŹc behaviors given
  by Enumerable are deïŹned 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 deïŹne #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 modiïŹes each member according to
  instructions in a block and returns the modiïŹed 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"]

Weitere Àhnliche Inhalte

Ähnlich wie Enumerables

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
Ian 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 Jasmine
Paulo Ragonha
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 

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

Mehr von Blazing Cloud

RSpec Quick Reference
RSpec Quick ReferenceRSpec Quick Reference
RSpec Quick Reference
Blazing Cloud
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
Blazing Cloud
 
Routes Controllers
Routes ControllersRoutes Controllers
Routes Controllers
Blazing Cloud
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Blazing Cloud
 

Mehr von 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
 

KĂŒrzlich hochgeladen

+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...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

KĂŒrzlich hochgeladen (20)

+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...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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 ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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...
 
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
 
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

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-speciïŹc behaviors. ‱ The class requiring the Enumerable module must have an #each method because the additional collection-speciïŹc behaviors given by Enumerable are deïŹned 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 deïŹne #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 modiïŹes each member according to instructions in a block and returns the modiïŹed 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"]