SlideShare a Scribd company logo
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"]

More Related Content

PPTX
Building YourClassical
PDF
Guitar Effects with the HTML5 Audio API
PDF
Desymfony 2011 - Habemus Bundles
PDF
Jetpack Compose - A Lightning Tour
PDF
How to eat Cucmber
PDF
Evented programming
PPTX
Ruby Enumerable
PDF
Ruby cold cuts_2
Building YourClassical
Guitar Effects with the HTML5 Audio API
Desymfony 2011 - Habemus Bundles
Jetpack Compose - A Lightning Tour
How to eat Cucmber
Evented programming
Ruby Enumerable
Ruby cold cuts_2

Similar to Enumerables (20)

DOCX
Enumerables
PDF
Blocks by Lachs Cox
PDF
Ruby on Rails - Introduction
PDF
Deep Dive Into Swift
PDF
Ruby on Rails
PDF
Odoo from 7.0 to 8.0 API
PDF
Odoo - From v7 to v8: the new api
PPTX
PHP PPT FILE
KEY
Desarrollando aplicaciones web en minutos
PDF
Let’s Talk About Ruby
PPTX
Intro to ruby
KEY
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
PDF
Template rendering in rails
PDF
Rails 3 overview
PDF
Cocoa Design Patterns in Swift
PDF
Rest with-spray
PDF
I Phone On Rails
PPTX
Workshop JavaScript ES6+
PDF
Chaining and function composition with lodash / underscore
PDF
Working with Javascript in Rails
Enumerables
Blocks by Lachs Cox
Ruby on Rails - Introduction
Deep Dive Into Swift
Ruby on Rails
Odoo from 7.0 to 8.0 API
Odoo - From v7 to v8: the new api
PHP PPT FILE
Desarrollando aplicaciones web en minutos
Let’s Talk About Ruby
Intro to ruby
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Template rendering in rails
Rails 3 overview
Cocoa Design Patterns in Swift
Rest with-spray
I Phone On Rails
Workshop JavaScript ES6+
Chaining and function composition with lodash / underscore
Working with Javascript in Rails
Ad

More from Blazing Cloud (20)

PDF
Rails ORM De-mystifying Active Record has_many
PDF
Active Record Introduction - 3
PDF
Rails Class Intro - 1
PDF
Your first rails app - 2
PDF
RSpec Quick Reference
PDF
Extending rails
KEY
2day Ruby Class Intro
KEY
Mobile Lean UX
KEY
Interactive Graphics
KEY
Interactive Graphics w/ Javascript, HTML5 and CSS3
KEY
Form helpers
KEY
Intro to Ruby (and RSpec)
KEY
What you don't know (yet)
KEY
Introduction to Rails
KEY
ActiveRecord
KEY
Ruby on Rails Class intro
KEY
Ruby on rails toolbox
KEY
Routes Controllers
KEY
Test Driven Development
KEY
Active Record
Rails ORM De-mystifying Active Record has_many
Active Record Introduction - 3
Rails Class Intro - 1
Your first rails app - 2
RSpec Quick Reference
Extending rails
2day Ruby Class Intro
Mobile Lean UX
Interactive Graphics
Interactive Graphics w/ Javascript, HTML5 and CSS3
Form helpers
Intro to Ruby (and RSpec)
What you don't know (yet)
Introduction to Rails
ActiveRecord
Ruby on Rails Class intro
Ruby on rails toolbox
Routes Controllers
Test Driven Development
Active Record
Ad

Recently uploaded (20)

PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Spectroscopy.pptx food analysis technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
OMC Textile Division Presentation 2021.pptx
A comparative analysis of optical character recognition models for extracting...
Unlocking AI with Model Context Protocol (MCP)
Spectroscopy.pptx food analysis technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
SOPHOS-XG Firewall Administrator PPT.pptx
Empathic Computing: Creating Shared Understanding
Mobile App Security Testing_ A Comprehensive Guide.pdf
cloud_computing_Infrastucture_as_cloud_p
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Network Security Unit 5.pdf for BCA BBA.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Encapsulation theory and applications.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Assigned Numbers - 2025 - Bluetooth® Document
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

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"]