Ruby 块(Block)和迭代器(Iterator)在 Ruby 编程中有着广泛的应用场景
each
方法遍历数组、哈希表等集合。array = [1, 2, 3, 4, 5]
array.each { |element| puts element }
map
、select
和 reduce
等函数都使用了代码块。array = [1, 2, 3, 4, 5]
squared_array = array.map { |number| number * number }
def fibonacci(n)
a, b = 0, 1
(0...n).each do |i|
yield a
a, b = b, a + b
end
end
fibonacci(5).each { |number| puts number }
array = [1, 2, 3, 4, 5]
result = array.map { |number| number * 2 }.select { |number| number % 3 == 0 }
class MyRange
def initialize(start, end)
@start = start
@end = end
end
def each(&block)
current = @start
while current <= @end
block.call(current)
current += 1
end
end
end
MyRange.new(1, 5).each { |number| puts number }
总之,Ruby 块和迭代器在 Ruby 编程中具有广泛的应用场景,它们可以帮助你编写更简洁、高效和可重用的代码。