Friday, February 16, 2007

From VB to Ruby - Creating Objects via COM

Many developers looking to take up Ruby on MS Windows have experience with Visual Basic, VBA and VBScript. There are millions of examples of VB code out there, and these can help you get up to speed with Ruby, especially in areas such as Microsoft Office automation. Here are a few tips when moving from VB to Ruby:

  • Require the win32ole library at the top of your script.
  • VB requires the Set statement when binding an object to a variable; Ruby does not.
  • In place of VB's CreateObject function, use Ruby's method.
  • In place of VB's GetObject function, use Ruby's WIN32OLE.connect method to connect to an existing instance of an object.
  • Remove all Dim statements; Ruby does not use them.

Dim xl
Dim ol
Set xl = CreateObject("Excel.Application')
Set ol= GetObject(,"Outlook.Application')


require 'win32ole'
xl ="Excel.Application")
ol = WIN32OLE.connect("Outlook.Application")

More VB-to-Ruby tips to follow. Let me know if there's anything in particular you'd like to see.


Unknown said...

Excellent example. Do you have to release the COM object when you're done with it? Or will the memory get cleaned up automatically?

David Mullet said...

Ruby's garbage collection usually does a good job cleaning up COM objects. Beyond simple scripts, though, I prefer to explicitly release the COM objects (xl = nil). In object hierarchies such as Excel, you'll want to release objects in reverse of the order created.

Vasudev Ram said...

Good post again.

The other post "Simple Output to Excel-compatible files" is a good idea too, to speed up the writes.

>Let me know if there's anything in particular you'd like to see.

Could you please post some about using Word with Ruby via OLE?

Great stuff ... I'll blog about your blog, also tell my friends about it ...

Vasudev Ram

Anonymous said...

strHost = "."
Const HKLM = &H80000002
Set objReg = GetObject("winmgmts://" & strHost & _
Const strBaseKey = _
objReg.EnumKey HKLM, strBaseKey, arrSubKeys

For Each strSubKey In arrSubKeys
intRet = objReg.GetStringValue(HKLM, strBaseKey & strSubKey, _
"DisplayName", strValue)
If intRet <> 0 Then
intRet = objReg.GetStringValue(HKLM, strBaseKey & strSubKey, _
"QuietDisplayName", strValue)
End If
If (strValue <> "") and (intRet = 0) Then
WScript.Echo strValue
End If

How to convert this VB script to ruby???