enumeration - What is the advantage of creating an enumerable object using to_enum in Ruby? -


Why can you create a proxy reference instead of using the to_enum method rather than using an object instead of an object in Ruby? I can not think of any practical use for this, I am trying to understand this concept & amp; Where anyone can use it, but all the examples I look very trivial.

For example, why use:

  "hello" .enum_for (: each_char). Map {| C | C.succ}  

instead of

  "hello" .each_char.map {| C | C.succ}  

I know this is a very simple example, do anyone have real world examples?

string # every_char in your example There is no reason to use to_enum ; Both will have the same effect.

Some methods have not returned a calculator, however. You may need to use the to_enum

  # how many elements array their position in the cure [4, 1, 2, 0] .to_enum (: count) .each_with_index {| elem, index | Elem == index} # = & gt; 2  

Another As an example, use the array # product , #uniq and #uniq! to accept the block in 1.9.2 It was changed, but to maintain consistency, without a block, a calculator can not return. Anyone still "manually" to get the user to to_enum can be used:

  'backports / 1.9.2 / Array / Product '# is required or use Ruby 1.9.2+ # To avoid generating a large arbitrary array: e = many_moves.to_enum (: Products, many_records) e.any? Do it Step, reaction | # The main use of the end of some criteria  

to_enum is when you are implementing your own repetition method, you will usually be in the form of the first line :

  def my_each back to_enum: my_each until block_life is not? # ... end  

Comments