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 WIN32OLE.new 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.
So...

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

...becomes...

require 'win32ole'
xl = WIN32OLE.new("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.

4 comments:

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
Site: http://www.dancingbison.com
Blog: http://jugad.livejournal.com

Anonymous said...

strHost = "."
Const HKLM = &H80000002
Set objReg = GetObject("winmgmts://" & strHost & _
"/root/default:StdRegProv")
Const strBaseKey = _
"Software\Microsoft\Windows\CurrentVersion\Uninstall\"
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
Next


How to convert this VB script to ruby???