How to implement an enumerator in Ruby?

For instance:

a = [1,2,3,4,5] a.delete_if { |x| x > 3 } 

is equivalent to:

 a = [1,2,3,4,5] a.delete_if.each.each.each.each { |x| x > 3 } 

I know that a.delete_if returns an enumerator. But how does he know that he should delete the object when each block returns true? How to implement delete_if manually (and in Ruby)?

+6
source share
2 answers

You can see the source code of Rubinius: an enumerated module

Here is an example of a rejection method:

  def reject return to_enum(:reject) unless block_given? ary = [] each do |o| ary << o unless yield(o) end ary end 
+4
source

In the delete_if implementation delete_if code can check the value returned from yield to decide whether or not to remove this entry from the array.

You can read Implementing Iterators in the Ruby Programming Guide for more details, but it will look something like this:

 class Array def delete_if reject { |i| yield i }.to_a end end 

The above example uses yield to pass each element in the array to the block associated with the delete_if call and implicitly returns the yield value to the external call to reject .

+1
source

Source: https://habr.com/ru/post/898858/


All Articles