Transformation Thursday - C# to Ruby, Referencing and using other libraries

August 7, 2014

I am learning Ruby and thought it would be useful to other .NET developers who are coming to Ruby to understand the differences.

I’ve covered:

Today I wanted to take a look at using and referencing other libraries. In the .NET world we are fortunate enough to have one of the best if not the best IDEs in Visual Studio. In Visual Studio it is a matter of right-click, add Reference and you select the assembly you wish. Once you have added the reference you want the next step is to add a using statement to the class file where you will be using the referenced assembly’s functionality.

Here is a class declaration with a few using statements needed to send an email in C#.

using System.Net;
using System.Net.Mail;

namespace Foo {
	class Bar {

		void SendEmail(string to, string from, string subject, string body) {
		  // implementation
		}
	}
}

So how do you go ahead and do the same in Ruby? Let me introduce you to the require and load keyword. Require, and Load are global functions defined in Object but are used like language keywords.

There is a small difference between require and load. The load keyword includes the Ruby source file every time it is called. Require which is more commonly used will only include the source file once and then caches it.

If you were paying attention you would have noticed I mentioned source files, Ruby is a scripting language it does not compile down to a dynamic link library or similar. When using require or load there is no need to include the ‘.rb’ file extension.

The exact syntax to require or load a Ruby source file is

require 'net/smtp'

module Foo
	class Bar
		def send_email(to, from, subject, body)
		  # implementation
	end
end

or

load 'net/smtp'

module Foo
	class Bar
		def send_email(to, from, subject, body)
		  # implementation
	end
end

Pretty simple and straightforward, that is the theme in Ruby. We have covered the basic structure of a Ruby program. In the next Transformation Thursday post, I would like to circle back and look at Modules once more.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus