Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby: How to create a custom iteration method for a Enumerator Object?

Lets say, we have an Array of Strings named words and I want to instantiate a special Enumerator on it which only counts Strings with the length != 3. Here is my proposal:

def words.n_each
  select{|x| x.length != 3}.each do |y|
    yield y
  end
end

e4 = words.enum_for(:n_each)
e4.each do |w|
  puts w
end

But there has to be a more smarter rubyish way to include the mechanics of the n_each method inside a codeblock at the time of instantiation of the Enumerator. But how?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Is lazy what you are looking for?

p e4 = ["aaa","c","foo","aaaa"].lazy.reject{|s| s.size == 3 } # => <Enumerator::Lazy: ["aaa", "c", "foo", "aaaa"]>:reject>

e4.each do |w|
  puts w
end

prints

c
aaaa
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading