Iterate through an Ruby Array and get(yield or return) each item in the array

I have an array and I need to create a class method named “each” to yield or return (not sure what the difference is of those or which I need to use if any) each item in the array when the method is called.

Do I need to use return instead of yield or neither?

class Sum

 def initialize
   @sum =  Array.new
 end

 def each
 @sum.each do |item|
   yield item
 end 

end

  • Dradis 2.9 not installing on windows 8 OS 64 bit
  • Collapse consecutive 'same' elements in array
  • why does subtraction between dates return a Rational type?
  • How to stop Savon from adding prefixes to soap.body
  • Ruby metaclasses: why three when defined singleton methods?
  • Calling ruby method without instantiating class
  • How to stop God from leaving stale Resque worker processes?
  • Rails attachments inline are not shown correctly in gmail
  • 3 Solutions collect form web for “Iterate through an Ruby Array and get(yield or return) each item in the array”

    You could include Enumerable and implement each and get a lot of functionality for free.

    class Sum
      def initialize
        @sum = []
      end
    
      def each &block
        @sum.each &block
      end
    end
    

    This will yield each item of the collection or if you do not provide a block it will return you an enumerator just like a normal Array would

    Are you attempting to write a class that acts like an iterator? That provides it’s own each form? If so, then this is the pattern for doing so with a ruby class:

    class MyIterator
      include Enumerable
    
      def initialize data=[]
        @data = data
      end 
    
      def each
        @data.each do |item|
          yield item
        end 
      end 
    end
    
    m = MyIterator.new [1,2,3,4]
    
    m.each do |item|
      puts "item=#{item}"
    end
    
    puts m.map(&:next)
    

    The for_each method iterates over the array (@data) and yields each of the values to the block.

    As @jan-dvorak pointed out, including Enumerable and naming the method each gives additional benefits, such as being able to call map directly on the object.

    Assuming that this is homework, and using the existing each method is not allowed:

    class Sum
      def initialize
        @values = []
      end
      def homework_each
        0.upto(@values.length-1){ |i| yield @values[i] }
      end
    end
    

    However, your code as written works, modulo the fact that you’re missing an end, and also you’re missing any way to populate your array with values.

    Ruby is the best programming language in the world - Ruby on Rails.