What does Ruby have that Python doesn’t, and vice versa?

Ruby has the concepts of blocks, which are essentially syntactic sugar around a section of code; they are a way to create closures and pass them to another method which may or may not use the block. A block can be invoked later on through a yield statement.

For example, a simple definition of an each method on Array might be something like:

class Array
  def each
    for i in self  
      yield(i)     # If a block has been passed, control will be passed here.
    end  
  end  
end  

Then you can invoke this like so:

# Add five to each element.
[1, 2, 3, 4].each{ |e| puts e + 5 }
> [6, 7, 8, 9]

Python has anonymous functions/closures/lambdas, but it doesn’t quite have blocks since it’s missing some of the useful syntactic sugar. However, there’s at least one way to get it in an ad-hoc fashion. See, for example, here.

Leave a Comment