Search code examples
rubyenumerable

how implement a function to iterate over if its passed a Range


I'm creating my own version of .each method in Ruby and I'm having trouble implementing it to work for the input of a Range (1..10).

module Enumerable
  # @return [Enumerable]
  def my_each
    return to_enum :my_each unless block_given?

    index = 0
    while index < size
      if is_a? Array
        yield self[index]
      elsif is_a? Hash
        yield keys[index], self[keys[index]]
      elsif is_a? Range
        yield self[index]
      end
      index += 1
    end
  end
end

I trying to get it to, if passed

r_list = (1..10)
r_list.my_each { |number| puts number }

The output would be

=> 
1
2
3
4
5
6
7
8
9
10

Solution

  • One technique, that changes very little of this implementation, would be to convert your range to an array.

    module Enumerable
      def my_each
        return to_enum :my_each unless block_given?
    
        index = 0
        while index < size
          if is_a? Array
            yield self[index]
          elsif is_a? Hash
            yield keys[index], self[keys[index]]
          elsif is_a? Range
            yield to_a[index]
          end
          index += 1
        end
      end
    end
    
    r_list = (1..10)
    puts r_list.my_each { |number| puts number }
    

    Result:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10