Iteratorهای پیشرفته در روبی
each_with_index، each_with_object، lazy، chunk و iteratorهای پیشرفته
Iteratorهای پیشرفته
each_with_index
["آ", "ب", "ج"].each_with_index { |val, i| puts "#{i}: #{val}" }
each_with_object
result = [1, 2, 3].each_with_object([]) do |n, arr|
arr << n ** 2
end
puts result.inspect # => [1, 4, 9]
lazy — ارزیابی تنبل
# بدون خطای حافظه
sum = (1..Float::INFINITY).lazy.select(&:even?).first(5)
puts sum.inspect # => [2, 4, 6, 8, 10]
chunk — گروهبندی متوالی
result = [1, 1, 2, 2, 3, 1, 1].chunk { |n| n }.to_a
puts result.inspect # => [[1, [1, 1]], [2, [2, 2]], [3, [3]], [1, [1, 1]]]
step
1.step(20, 5) { |n| puts n } # => 1, 6, 11, 16
upto / downto
1.upto(5) { |n| puts n }
5.downto(1) { |n| puts n }
cycle
["آ", "ب", "ج"].cycle.first(7)
# => ["آ", "ب", "ج", "آ", "ب", "ج", "آ"]
خلاصه
| متد | توضیح |
|---|---|
each_with_index | با ایندکس |
each_with_object | با accumulator |
lazy | ارزیابی تنبل |
chunk | گروهبندی متوالی |
cycle | تکرار بینهایت |
این مبحث بخشی از دوره آموزش کامل روبی است.