Ruby and Python: perspectives

I just realized something interesting.

In Ruby you mix in modules that add methods to objects that implement interfaces.

In Python you have functions that you use on objects that implement interfaces.

One easy example are enumerables/iterables: in Ruby, an object is enumerable if it implements the each method. The object can then mix in Enumerable to gain some methods that you can use:

f = File.new(".bashrc", "r")
lines = f.find_all { |l| l =~ /^[^#]/ }
# or lines = f.grep(/^[^#]/)

In Python, an object is iterable if it implements the __iter__ method, and the language “knows” how to use the iterators:

f = file(".bashrc", "r")
lines = [ l for l in f if not l.startswith("#") ]
# or lines = filter(lambda l: not l.startswith("#"), f)

other examples are any and all, which incidentally are what started the discussion with Francesco about this:

In Ruby, the any? method is added to every enumerable object that mixes in Enumerable:

lines.any? { |l| l =~ /^#/ }

In Python, any() is a built-in function (introduced in 2.5) which knows how to use any sequence:

any(l.startswith("#") for l in lines)

So Ruby works from the inside, and Python from the outside of objects. I think therefore that the next comparison between the two languages should not be side-by-side, but inside-and-out.