Peter's Blog

Redefining the Impossible

Ruby Blocks


Right now I'm working in Python yet I am already missing Ruby Blocks.

What I am doing is I am sending commands to firmware and processing the results. I have common code like this:

def DoCommand():
   try:
      SendCommand()
      oResults = GetResults()
      #
      # Process the results
      #
   except:
      ProcessError()

Different types of command yield different results and I have to duplicate all this with different result handling code. In ruby I could do it like this:

   1  def DoCommand()
   2     begin
   3        SendCommand()
   4        oResults = GetResults()
   5        #
   6        # Process the results
   7        #
   8        yield( oResults)
   9     rescue
  10        ProcessError()
  11     end
  12  end
Toggle Line Numbers

and call it like this

DoCommand() { |oResults| print oResults }

i.e. I pass the result handling code as a block and the block is executed within the exception handler.

There are many other ways I could structure this but using blocks seems like a nice efficient way to do it using a minimum of typing. For example, in python I could do it like this:

   1  def DoCommand( oResultHandler):
   2     try:
   3        SendCommand()
   4        oResults = GetResults()
   5        #
   6        # Process the results
   7        #
   8        oResultHandler( oResults)
   9     except:
  10        ProcessError()
  11  
  12  def HandleOneKindOfResult( oResults)
  13    print oResults
  14  
  15  DoCommand( HandleOneKindOfResult)
Toggle Line Numbers

I have to define multiple functions like HandleOneKindOfResult and I have to think of names to give them where in ruby these are just nameless blocks.

So why am I doing what I am doing in python and not ruby? Two reasons:

  • short deadline
  • I am using wxPython, pyserial and pyexe and don't know of or have experience of any ruby equivalents.

Filed under: python ruby

2 Comments

jz Says:

over 2 years ago

You can accomplish similar effect in Python using lambda functions. Instead of defining funtion using def, you can define it in place using lambda syntax. Function is then nameless, imo lambdas are similar to ruby blocks.

Unfortunately there are some limitation what can be used in lambda functions (f.e. no print statement), just calling other functions that returns value or expression that yields value - functional approach.

Syntax - example: doCommand(lambda x: myfunc1("test", x, 1, myfunc2())

Peter Says:

over 2 years ago

I think I was under the impression that lambdas were going to be deprecated, or am I thinking of the map comment et al?

Blocks can be multi-line, I'm not sure that is the case for lambda's. You do have a point though.

Peter

Sorry but comments on this post are now closed.