Module: Enumerable
- Defined in:
- lib/qualitysmith_extensions/symbol/match.rb,
lib/qualitysmith_extensions/enumerable/enum.rb
Instance Method Summary collapse
-
#enum(iterator = :each) ⇒ Object
The core Enumerable module provides the following enumerator methods; *
enum_cons()*enum_slice()*enum_with_index()but for some reason they didn’t provide a genericenum()method for the cases they didn’t think of!. - #grep_with_regexp_support_for_symbols(pattern, &block) ⇒ Object
Instance Method Details
#enum(iterator = :each) ⇒ Object
The core Enumerable module provides the following enumerator methods;
-
enum_cons() -
enum_slice() -
enum_with_index()
but for some reason they didn’t provide a generic enum() method for the cases they didn’t think of!
enum lets you turn any iterator into a general-purpose Enumerator, which, according to the RDocs, is “A class which provides a method ‘each’ to be used as an Enumerable object.”
This lets you turn any ‘each'-type iterator (each_byte, each_line, …) into a ’map‘-type iterator (one that returns a collection), or into an array, etc.
So if an object responds to :each_line but not to :map_lines or :lines, you could just do:
object.enum(:each_line).map { block }
object.enum(:each_line).min
object.enum(:each_line).grep /pattern/
lines = object.enum(:each_line).to_a
If no iterator is specified, :each is assumed:
object.enum.map { block }
More examples:
Dir.new('.').enum.to_a
#=> ['file1', 'file2']
"abc".enum(:each_byte).map{|byte| byte.chr.upcase}
#=> ["A", "B", "C"]
39 40 41 |
# File 'lib/qualitysmith_extensions/enumerable/enum.rb', line 39 def enum(iterator = :each) Enumerable::Enumerator.new(self, iterator) end |
#grep_with_regexp_support_for_symbols(pattern, &block) ⇒ Object
88 89 90 91 92 |
# File 'lib/qualitysmith_extensions/symbol/match.rb', line 88 def grep_with_regexp_support_for_symbols(pattern, &block) map { |element| element.is_a?(Symbol) ? element.to_s : element }.grep_without_regexp_support_for_symbols(pattern, &block) end |