Sunday, February 8, 2009

Iterator in Ruby and Python

Unlike Java, both languages support real iterator not just iterator object. The following code shows how to create and use iterator in Python.

def from_1_to_5():
for i in [1, 2, 3, 4, 5]:
yield i

for num in from_1_to_5():
print num

The following code shows how to make it in Ruby. Desides a style similar to Python, Ruby can use iterator with block.

def iterator
for i in [1, 2, 3, 4, 5]
yield(i)
end
end

# invoke iterator in a way similar to Python
call_block do |num|
puts "#{num}"
end

# invoke iterator with the use of block
call_block { |num| puts "#{num}" }

No comments: