如果传递了范围,如何实现一个函数进行迭代

问题描述 投票:0回答:1

[我正在Ruby中创建自己的.each方法版本,但是我难以实现将其用于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

我试图通过它,如果通过的话

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

输出为

=> 
1
2
3
4
5
6
7
8
9
10
ruby enumerable
1个回答
0
投票

一种技术,对此实现的更改很小,是将范围转换为数组。

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 }

结果:

1
2
3
4
5
6
7
8
9
10
© www.soinside.com 2019 - 2024. All rights reserved.