method

enum_for

v1_8_7_72 - Show latest stable - Class: Object
enum_for(...)
public

Returns Enumerable::Enumerator.new(self, method, *args).

e.g.:

   str = "xyz"

   enum = str.enum_for(:each_byte)
   a = enum.map {|b| '%02x' % b } #=> ["78", "79", "7a"]

   # protects an array from being modified
   a = [1, 2, 3]
   some_method(a.to_enum)

2Notes

Needs requiring 'enumerator' to work

yonosoytu · Aug 23, 20084 thanks

This method needs that you

require 'enumerator'

for this method to be available.

map_with_index

rob-twf · May 26, 20093 thanks

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