如果它传递了一个范围,如何实现一个函数来迭代
how implement a function to iterate over if its passed a Range
我在 Ruby 中创建了我自己的 .each 方法版本,但我无法实现它来处理范围 (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
一种技术,对这个实现的改变很小,就是将范围转换为数组。
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
我在 Ruby 中创建了我自己的 .each 方法版本,但我无法实现它来处理范围 (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
一种技术,对这个实现的改变很小,就是将范围转换为数组。
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