Flowdock
enum_for(*args) public

Creates a new Enumerator which will enumerate by on calling method on obj.

method

the method to call on obj to generate the enumeration

args

arguments that will be passed in method in addition

to the item itself.  Note that the number of args
must not exceed the number expected by +method+

Example

str = "xyz"

enum = str.enum_for(:each_byte)
enum.each { |b| puts b }
# => 120
# => 121
# => 122

# protect an array from being modified by some_method
a = [1, 2, 3]
some_method(a.to_enum)
Show source
Register or log in to add new notes.
August 23, 2008
3 thanks

Needs requiring 'enumerator' to work

This method needs that you

require 'enumerator'

for this method to be available.

May 27, 2009 - (>= v1_8_6_287)
2 thanks

map_with_index

If you want to access the element index when using map, you can do it with enum_for:

(1..6).enum_for(:each_with_index).map { |v, i| "index: #{i} value: #{v}" }
#=> ["index: 0 value: 1", "index: 1 value: 2", "index: 2 value: 3", "index: 3 value: 4", "index: 4 value: 5", "index: 5 value: 6"]