iterator (array.each) as return value of method in ruby -


i have class :

class myarray   attr_accessor :data    def initialize(my_object = nil)     @data = array[*my_object]   end    def <<(y)     @data << y   end    def each     @data.each   end end 

and using this

subject = myarray.new([2, 5, 3])   d = []      subject.each { |i|     d <<   } 

the problem is, not iterate once through -subject.each-. should return "each" value array method return value? how return iterator itself?

i tried , not working :

  def each     [2,5,3].each   end 

thanks "meagar" , "erik allik" have right answer : (only "def each" method has changed)

class myarray   attr_accessor :data    def initialize(my_object = nil)     @data = array[*my_object]   end    def <<(y)     @data << y   end    def each(&block)     @data.each(&block)   end end 

the problem each {block} invoking each on array , passing in block argument method. block argument being ignored.

if want work, need forward block nested each call:

class test   def each(&block)      [1, 2, 3].each(&block)   end end  test.new.each |i|   puts end 

if want return iterator, you're free so, have invoke each on iterator, , give it block:

class test   def each     [1, 2, 3].each   end end  test.new.each.each |i|    puts end 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -