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 編程中具有廣泛的應用場景,它們可以幫助你編寫更簡潔、高效和可重用的代碼。