In my continuing quest to expand my knowledge of all things Computer Science, I stumbled across the Generator topic on Wikipedia. I ended up here after reading an excerpt from Python Cookbook.
The Wikipedia article describes a generator as something that looks like a function but behaves like an iterator. The interesting thing to me is that they can be used to build endless lists.
For example, the Python Cookbook gives several generators that will list all prime numbers (given enough time). The Wikipedia article gives another way of generating prime numbers.
I was surprised that Ruby wasn’t mentioned in the Wikipedia article so I set off on a search for information about Ruby generators. Unfortunately, most of what I found was dealing with code generators for Rails which is something else entirely.
The Ruby Documentation contains a description of the Generator class with a brief example. I was able to use this to convert Wikipedia’s simple prime number generator to Ruby.
require 'generator'
g = Generator.new do |g|
n = 2
p = []
while true
if p.all? { |f| n % f != 0 }
g.yield n
p << n
end
n += 1
end
end
Using this code, each time you call g.next
it will return the next prime number starting with 2. For example, this will print the first 25 prime numbers:
for i in 1..25
puts g.next
end
If you examine the source code in both Python and Ruby you’ll find that they are remarkably similar. The only change is basically replacing Python’s any
function with a call to Ruby’s Enumerable#all?
.
The more I learn about Python and Ruby, the more similar I realize they are. I have yet to find anything in Python that can’t be done just as easily in Ruby or vice-versa.