SlideShare ist ein Scribd-Unternehmen logo
1 von 18
A powerful Ruby Module for Collections Enumerable by Sarah Allen and Liah Hansen
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"]

Weitere ähnliche Inhalte

Ähnlich wie Ruby Enumerable

4 Regex Enumerables
4 Regex Enumerables4 Regex Enumerables
4 Regex Enumerablesliahhansen
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails Hung Wu Lo
 
Perl Teach-In (part 1)
Perl Teach-In (part 1)Perl Teach-In (part 1)
Perl Teach-In (part 1)Dave Cross
 
Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into SwiftSarath C
 
You are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfYou are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfeyebolloptics
 
Metaprogramming With Ruby
Metaprogramming With RubyMetaprogramming With Ruby
Metaprogramming With RubyFarooq Ali
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishGrails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishSven Haiges
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Platonov Sergey
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)mussawir20
 
Power Theming
Power ThemingPower Theming
Power Themingdrkdn
 
Using The Google Collections Library For Java
Using The Google Collections Library For JavaUsing The Google Collections Library For Java
Using The Google Collections Library For JavaGoogleTecTalks
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecordMark Menard
 
Rails3 for Rails2 developers
Rails3 for Rails2 developersRails3 for Rails2 developers
Rails3 for Rails2 developersalkeshv
 

Ähnlich wie Ruby Enumerable (20)

4 Regex Enumerables
4 Regex Enumerables4 Regex Enumerables
4 Regex Enumerables
 
Elastic tire demo
Elastic tire demoElastic tire demo
Elastic tire demo
 
Combres
CombresCombres
Combres
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails
 
Perl Teach-In (part 1)
Perl Teach-In (part 1)Perl Teach-In (part 1)
Perl Teach-In (part 1)
 
Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into Swift
 
You are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdfYou are given a specification for some Java classes as follows.  A.pdf
You are given a specification for some Java classes as follows.  A.pdf
 
Metaprogramming With Ruby
Metaprogramming With RubyMetaprogramming With Ruby
Metaprogramming With Ruby
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishGrails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
 
Power Theming
Power ThemingPower Theming
Power Theming
 
Init() Day 4
Init() Day 4Init() Day 4
Init() Day 4
 
Using The Google Collections Library For Java
Using The Google Collections Library For JavaUsing The Google Collections Library For Java
Using The Google Collections Library For Java
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Intro to Rails ActiveRecord
Intro to Rails ActiveRecordIntro to Rails ActiveRecord
Intro to Rails ActiveRecord
 
Rails3 for Rails2 developers
Rails3 for Rails2 developersRails3 for Rails2 developers
Rails3 for Rails2 developers
 
Enumerable
EnumerableEnumerable
Enumerable
 
SVCC Intro to Grails
SVCC Intro to GrailsSVCC Intro to Grails
SVCC Intro to Grails
 

Mehr von Sarah Allen

Internet security: a landscape of unintended consequences
Internet security: a landscape of unintended consequencesInternet security: a landscape of unintended consequences
Internet security: a landscape of unintended consequencesSarah Allen
 
RTMP: how did we get to now? (Demuxed 2019)
RTMP: how did we get to now? (Demuxed 2019)RTMP: how did we get to now? (Demuxed 2019)
RTMP: how did we get to now? (Demuxed 2019)Sarah Allen
 
Communication is a Technical Skill
Communication is a Technical SkillCommunication is a Technical Skill
Communication is a Technical SkillSarah Allen
 
Improving Federal Government Services
Improving Federal Government ServicesImproving Federal Government Services
Improving Federal Government ServicesSarah Allen
 
Transparency Wins
Transparency WinsTransparency Wins
Transparency WinsSarah Allen
 
A Short History of Computers
A Short History of ComputersA Short History of Computers
A Short History of ComputersSarah Allen
 
Making Software Fun
Making Software FunMaking Software Fun
Making Software FunSarah Allen
 
Power of Transparency
Power of TransparencyPower of Transparency
Power of TransparencySarah Allen
 
Designing for Fun
Designing for FunDesigning for Fun
Designing for FunSarah Allen
 
Ruby in the US Government for Ruby World Conference
Ruby in the US Government for Ruby World ConferenceRuby in the US Government for Ruby World Conference
Ruby in the US Government for Ruby World ConferenceSarah Allen
 
Identities of Dead People
Identities of Dead PeopleIdentities of Dead People
Identities of Dead PeopleSarah Allen
 
3 Reasons Not to Use Ruby
3 Reasons Not to Use Ruby 3 Reasons Not to Use Ruby
3 Reasons Not to Use Ruby Sarah Allen
 
Ruby Nation: Why no haz Ruby?
Ruby Nation: Why no haz Ruby?Ruby Nation: Why no haz Ruby?
Ruby Nation: Why no haz Ruby?Sarah Allen
 
Why no ruby in gov?
Why no ruby in gov?Why no ruby in gov?
Why no ruby in gov?Sarah Allen
 
People Patterns or What I learned from Toastmasters
People Patterns or What I learned from ToastmastersPeople Patterns or What I learned from Toastmasters
People Patterns or What I learned from ToastmastersSarah Allen
 
Blazing Cloud: Agile Product Development
Blazing Cloud: Agile Product DevelopmentBlazing Cloud: Agile Product Development
Blazing Cloud: Agile Product DevelopmentSarah Allen
 
Crowdsourced Transcription Landscape
Crowdsourced Transcription LandscapeCrowdsourced Transcription Landscape
Crowdsourced Transcription LandscapeSarah Allen
 
Lessons Learned Future Thoughts
Lessons Learned Future ThoughtsLessons Learned Future Thoughts
Lessons Learned Future ThoughtsSarah Allen
 
Mobile Web Video
Mobile Web VideoMobile Web Video
Mobile Web VideoSarah Allen
 

Mehr von Sarah Allen (20)

Internet security: a landscape of unintended consequences
Internet security: a landscape of unintended consequencesInternet security: a landscape of unintended consequences
Internet security: a landscape of unintended consequences
 
RTMP: how did we get to now? (Demuxed 2019)
RTMP: how did we get to now? (Demuxed 2019)RTMP: how did we get to now? (Demuxed 2019)
RTMP: how did we get to now? (Demuxed 2019)
 
Communication is a Technical Skill
Communication is a Technical SkillCommunication is a Technical Skill
Communication is a Technical Skill
 
Improving Federal Government Services
Improving Federal Government ServicesImproving Federal Government Services
Improving Federal Government Services
 
Transparency Wins
Transparency WinsTransparency Wins
Transparency Wins
 
A Short History of Computers
A Short History of ComputersA Short History of Computers
A Short History of Computers
 
Making Software Fun
Making Software FunMaking Software Fun
Making Software Fun
 
Power of Transparency
Power of TransparencyPower of Transparency
Power of Transparency
 
Designing for Fun
Designing for FunDesigning for Fun
Designing for Fun
 
Ruby in the US Government for Ruby World Conference
Ruby in the US Government for Ruby World ConferenceRuby in the US Government for Ruby World Conference
Ruby in the US Government for Ruby World Conference
 
Identities of Dead People
Identities of Dead PeopleIdentities of Dead People
Identities of Dead People
 
Let's pretend
Let's pretendLet's pretend
Let's pretend
 
3 Reasons Not to Use Ruby
3 Reasons Not to Use Ruby 3 Reasons Not to Use Ruby
3 Reasons Not to Use Ruby
 
Ruby Nation: Why no haz Ruby?
Ruby Nation: Why no haz Ruby?Ruby Nation: Why no haz Ruby?
Ruby Nation: Why no haz Ruby?
 
Why no ruby in gov?
Why no ruby in gov?Why no ruby in gov?
Why no ruby in gov?
 
People Patterns or What I learned from Toastmasters
People Patterns or What I learned from ToastmastersPeople Patterns or What I learned from Toastmasters
People Patterns or What I learned from Toastmasters
 
Blazing Cloud: Agile Product Development
Blazing Cloud: Agile Product DevelopmentBlazing Cloud: Agile Product Development
Blazing Cloud: Agile Product Development
 
Crowdsourced Transcription Landscape
Crowdsourced Transcription LandscapeCrowdsourced Transcription Landscape
Crowdsourced Transcription Landscape
 
Lessons Learned Future Thoughts
Lessons Learned Future ThoughtsLessons Learned Future Thoughts
Lessons Learned Future Thoughts
 
Mobile Web Video
Mobile Web VideoMobile Web Video
Mobile Web Video
 

Ruby Enumerable

  • 1. A powerful Ruby Module for Collections Enumerable by Sarah Allen and Liah Hansen
  • 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
  • 6. 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
  • 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"]

Hinweis der Redaktion

  1. its fine to use is_a in irb..in code should use respond_to?
  2. Our first example below returns any member which contains an &apos;a&apos;. The grep method also accepts a block, which is passed each matching value, &apos;collecting&apos; the results returned and returning those as shown in the second example.