Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如果一个函数通过一个范围,如何实现该函数进行迭代_Ruby_Enumerable - Fatal编程技术网

Ruby 如果一个函数通过一个范围,如何实现该函数进行迭代

Ruby 如果一个函数通过一个范围,如何实现该函数进行迭代,ruby,enumerable,Ruby,Enumerable,我正在用Ruby创建自己版本的.each方法,但在实现它以处理范围(1..10)的输入时遇到了困难 输出将是 => 1 2 3 4 5 6 7 8 9 10 有一种技术对该实现的影响很小,那就是将范围转换为数组 module Enumerable def my_each return to_enum :my_each unless block_given? index = 0 while index < size if is_a? Arr

我正在用Ruby创建自己版本的.each方法,但在实现它以处理范围(1..10)的输入时遇到了困难

输出将是

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

有一种技术对该实现的影响很小,那就是将范围转换为数组

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 }

每个都不在可枚举的中是有原因的:每个可枚举对象都应该提供自己的每个,可枚举的中的方法可以依靠这些方法精确地提供对对象元素的迭代。也就是说。。。屈服<代码> Self.Read + index <代码>应该是好的。再对@ Amadan的评论,考虑<代码>可枚举αmap 。还有一种方法
Array#map
,当然
Array
包括
Enumerable
。我们发现
[1].method(:map).owner#=>数组
[1].method(:map).super#method.owner#=>可枚举
,因此
arr.map{…}
调用
Array#map
。每个类
C
都是一样的,包括
可枚举的
C
已经有一个方法
C#each
,因此您的
可枚举#each
将不会被使用。结果是,创建一个
可枚举的
方法
each
似乎毫无意义。
=> 
1
2
3
4
5
6
7
8
9
10
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