masa16 / narray

This repository contains OLD version of NArray. Please visit NEW version =>
https://github.com/ruby-numo/numo-narray
168 stars 28 forks source link

Make each return an Enumerator object if not given a block to iterate with #41

Open nat-n opened 10 years ago

nat-n commented 10 years ago

It would be useful if NArray provided a standard ruby Enumerator interface. All that would be required is for my_narray.each to return an Enumerator object, like my_array.each does when called without a block.

This would enable use cases such as my_narray.each.each_with_index { ... } or my_narray.each.map { ... } etc.

The follow monkey patch provides this functionality but I'm sure a better solution is possible.

class NArray
  alias_method :native_each, :each

  def each
    return enum_for :each unless block_given?
    native_each { |item| yield item }
  end
end
masa16 commented 10 years ago

Thank you for suggestion. https://github.com/masa16/narray/commit/67e8187f99cb048cd6533c2b9506deabf4eb8fb8