- Posted by Shay Friedman on June 28, 2010
So Epicenter and NDC are now over but that doesn’t mean I’m stopping evangelizing IronRuby!
So my next talks will take place in the upcoming DevLink conference which will be running in Lipscomb University, Nashville, TN, USA.
Currently I have 2 talks:
Practical IronRuby
Track: Open Source | Room: Ezell-E109 | Date: 7/8/2010 | Time: 11:30AM
Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. IronRuby version 1.0 will soon be released, unleashing the power of Ruby to the .NET world. In this session you will get familiar with the Ruby language and its amazing ecosystem and you will learn to take advantage of it in your everyday development tasks. Come and see how this great new addition to the .NET family makes your development process faster, clearer and happier!
Riding IronRuby on Rails
Track: Open Source | Room: Ezell-E109 | Date: 7/8/2010 | Time: 1:00PM
The most famous Ruby-driven framework is, by far, Ruby on Rails. With IronRuby, .NET developers can now take advantage of this incredible web framework without leaving their comfort zone. In this session, Shay Friedman will build an entire Web 2.0 site from scratch while using and explaining the key features of Ruby on Rails. Come and see what Ruby on Rails is all about and what's made it the success it is today.
-------------------------------
Even though both of my sessions are on the last day of the conference, I’ll be around during the other days as well so I’m looking forward to chat, discuss and drink beer with you!
See you there,
Shay.
- Posted by Shay Friedman on June 26, 2010
[if you have no idea what IronRuby is, read this first]
.NET has some common naming conventions that everybody uses. One of them is that namespace and class names are PascalCased. However, like in real life – rules are meant to be broken. In C#/VB.NET there is no real constraint on this convention – you can name your namespaces/classes using all lowercase or in any other way you want (and I ask, why?). Therefore, the next C# code is totally acceptable:
namespace demo
{
class library
{
public void Print()
{
Console.WriteLine("Yay! I've broken the rulez! I'm a smartass!");
}
}
}
The Problem
Unlike C#/VB.NET, in Ruby you must start namespace (which is called a module) and class names with a capital letter. And there you have it – clash of the titans.
Now, normally you wouldn’t care about that but if you’re using IronRuby, you’re right in the middle here. On the one hand, you’d expect IronRuby to allow you to use .NET classes with their original names but on the other hand, the Ruby language just doesn’t allow that.
The Solution
To solve this issue we must use some kind of a workaround. Luckily, IronRuby provide a pretty simple workaround. For example, consider the next C# classes (let’s assume this code is built into an assembly named demo.dll):
namespace demo
{
public class library
{
public void Print()
{
Console.WriteLine("Hello");
}
}
public class LibraryWithGoodName
{
public void Print()
{
Console.WriteLine("Hello");
}
}
}
This is how you use it from IronRuby:
require "demo.dll"
# Get the namespace object
Demo = Object.const_get("demo")
# Get the lowercase library class object
Library = Demo.const_get("library")
# Use the library class:
lib = Library.new
lib.Print
# Another alternative to create a library class instance in one line:
lib = Object.const_get("demo").const_get("library").new
lib.Print
# Use the LibraryWithGoodName class:
lib1 = Demo::LibraryWithGoodName.new
lib1.Print
All the best,
Shay.
- Posted by Shay Friedman on June 24, 2010
On the journey to cross the language barrier that stands between IronRuby and .NET developers, this post will teach you everything you need to know to start using IronRuby. And the intention is that it will not take you more than 25 minutes. So go grab a coffee and start reading.
….
I’m waiting… go get that coffee already!
….
………
…………
Good! Now that we’re ready to go, let’s start!
So, first task for you, which will take the first 15 minutes of our time is to learn Ruby. This is exactly the reason for my latest post – Learning Ruby in 15 Minutes. Go ahead and read it and then come back here.
……………
OK. Now that you know Ruby and we still have 10 minutes left to learn IronRuby. Not a lot of time but hey, that’s all we need.
First of all – Download and Install IronRuby
Well, to use IronRuby you must first download and install it. So if you have .NET 4 installed, download the IronRuby installer from here. Otherwise, download this version which supports .NET 2.0 SP1 and above. This will download an MSI file, so to install IronRuby just run the installer, then click Next, Next, Next and Finish. That’s it, you’re done.
Pay attention that IronRuby supports all the Ruby language features. Therefore, everything you’ve learned on the 15 minute Ruby course apply to IronRuby as well.
Running IronRuby Files
When running IronRuby files, the important thing to have is an IronRuby file… Ruby code files are usually saved with the .rb extension. Hence, after you have written your precious Ruby code, save it to a file with the .rb extension. For example, let’s say we save the next code in a file named hello.rb:
# Class definition
class Hello
def say_hello
puts "Hello!"
end
end
# The code that will get executed
hello = Hello.new
hello.say_hello
To run this file you will need to open the command prompt. This is done in Windows via the Start->Run dialog (shortcut: WinKey+R) – input cmd in this dialog and the command prompt will open. As soon as you have the cmd window opened, you can run IronRuby files.
Running IronRuby files is done using the IronRuby interpreter which exists within the ir.exe file. Therefore, the command to run IronRuby files starts with ir.exe followed by the file name. If the run file is placed within the current directory you only need to specify the name of the file. If it is located in a different folder, you need to specify the entire path. For example, the next cmd window screenshot shows running the hello.rb file from the previous sample:
Referencing .NET Assemblies
The expertise of IronRuby is its integration with .NET assemblies - you can load any .NET assembly and use it from Ruby code.
Doing so is just like loading other Ruby files – via the require method (which was mentioned on the Learning Ruby in 15 minutes post). All you need to do is to pass the name of the assembly (with or without the full path) to the require method:
require 'MyCustomAssembly.dll'
require 'C:\Demo\SomeAssembly.dll'
In case the assembly is located in the GAC or is signed, pass its strong name:
require "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
If you want to learn more about referencing .NET assemblies, look here.
Using .NET Assemblies
After you load .NET assemblies using the require method (or the other alternatives), you can use everything inside these assemblies. For this you need to be aware of a few things:
- The namespace delimiter in Ruby is ::. Therefore, System.Windows.Forms will be System::Windows::Forms in IronRuby.
- The method include is similar to C#’s using keyword so you can take advantage of it. For example: include System::Windows::Forms.
- When a .NET assembly is loaded into IronRuby context it goes through a name mangling process. This process converts the names of the .NET properties and methods to their equivalent Ruby name (because Ruby has different naming conventions). You will still be able to use the C# name, but it is important to be familiar with that.
The name mangling process converts the .NET’s CamelCase convention to Ruby’s lowercase_and_delimited convention. Read more about this process here.
The next sample demonstrates using the System.Windows.Forms assembly to create a simple form with a label via IronRuby. Pay attention to the names of the methods and properties which are the results of the name mangling process:
require "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
include System::Windows::Forms
# Create a form object
form = Form.new
# Create a label
label = Label.new
label.auto_size = true
# Set the text of the label
label.text = "IronRuby Rulezzzzz!!!"
# Add the label to the form
form.controls.add label
# Show the form
form.show_dialog
Conclusion
You have successfully crossed the language barrier! Congratulations!
This post and the one before it taught you all the basic stuff. Even though it is enough to get started, I think your experience with Ruby and IronRuby will be much more fulfilling after you learn more advanced subjects. There are numerous sites, tutorials and books ( *caugh* IronRuby Unleashed *caugh*) you can read and a great deal of forums and mailing lists where you can ask questions. So don’t be afraid to start, we’re all here to help!
Enjoy!
Shay.
- Posted by Shay Friedman on June 22, 2010
A problem I run into a lot when evangelizing IronRuby is the language barrier. Just like real life, people are scared when they visit a country where they do not know the local language. Same thing with C# developers who are afraid to learn other languages.
However, some languages are more easier to learn than others. For example, English would be much easier to learn than Hebrew. This is exactly the case with Ruby – it is a very easy-to-learn language and the title of this post is not a scam, I do mean to teach you all you need to know about Ruby in order to start working in the next 15 minutes. After you have these basics, my next post will be about IronRuby and the fundamentals you need to know when using it.
Sit tight, here we go.
Variables
Well, Ruby has a dynamic type system. This means that it really actually has a type system (unlike a lot of people think) but it is totally implicit. So to declare a variable you just write the name, followed by an equal sign and then the value:
# Creating variables
num = 1 # setting a variable named "num" with a numeric value of 1
str = "Hello" # setting a variable named "str" with a textual value of "Hello"
arr = [1, 2, 3] # setting a variable named "arr" with an array of 3 numbers - 1, 2 and 3
hash = { "key1" => "my value", "key2" => "another value" } # creating a hash with key value pairs
# Reading variables
num + 1 # adding 1 to num
puts str # prints the value of str to the console
arr[0] # retrieve the first value of the array
hash["key1"] # retrieve the value from the hash with the key of "key1"
Symbols
Symbols are a cool thing in Ruby. They are used in various cases and you will identify them by the colon in front of their name. You can think of them as enum values – they are not strings but they are not variables either – they are there to be used as keys to other values. You will run into them a lot with hashes. For example, instead of the hash I created on the previous sample, the next one would be more “correct”:
hash = { :key1 => "my value", :key2 => "another value" }
hash[:key1]
Conditions
Conditions in Ruby are pretty straight forward:
if condition then
# something
elsif other_condition then
# somethng else
else
# other something
end
The condition itself is very similar to C# – you use the == sign to compare between two values (or > and <). To concatenate multiple conditions, use the and and or keywords like if a > 1 and a < 5 then.
Additionally, Ruby conditions have a cool little twist – the unless condition. The unless condition is very similar to if. The difference between them is that unless is like if not. This means that you never need to write negative conditions like a != 1. Instead, you use the unless condition:
unless a == 1 then
# something
end
Reverse Conditions
To enhance the readability of the code, Ruby offers something that is called “reverse conditions”. This language feature enables writing one-line conditions with the action to do before the condition. For example, the next statement adds 1 to variable a if a is greater than 5:
Reverse conditions can be used with if as well as with unless.
Loops
Ruby features three loops out-of-the-box – while, until and for. while is the same as C#’s while:
while condition do
#something
end
The until condition is similar to the concept of the unless condition – it is the same as while not:
a = 0
until a == 5 do
puts a
a = a + 1
end
The for loop is similar to the foreach loop in C# – it iterates through a collection:
a = [1,2,3]
for item in a do
puts item
end
# prints
# 1
# 2
# 3
Apart for these loops, when coding Ruby you will find yourself using the enumeration capabilities of the different objects. For example, to run a loop 10 times, just use the times method of integer numbers:
10.times do |i|
print i
end
# prints: "0123456789"
Another way, if you want to loop over all the number from 5 to 9, you can use the upto or downto methods of integer numbers:
5.upto(9) do |i|
print i
end
# prints: "56789"
9.downto(5) do |i|
print i
end
# prints: "98765"
In addition, to loop over collections, you can call their each method (instead of using the for loop):
a = [1,2,3]
a.each do |item|
puts item
end
# prints:
# 1
# 2
# 3
Error Handling
Handling errors in Ruby is done very similar to C# or other languages. The flow is as such:
begin
# something risky
rescue SomeException => s # catch specific exception type (SomeException)
# and put in variable named s
puts "Oh no!"
rescue Exception => x # catch all exceptions and put in x
puts "Why??? Why???"
rescue # catch all exceptions without setting the exception to a variable
puts "The horror!!!!"
end
Notice that only one rescue block will be executed. If multiple rescue blocks match the raised exception, the first match will be executed and the rest will be ignored.
Blocks
Blocks are very common in Ruby. Actually, every time you see code that is enclosed inside do and end keywords or curly brackets {}, you see a block. You can think of blocks as anonymous methods in C#.
So as mentioned, there are two ways to define a block – inside do and end keywords or inside curly brackets. There is no major difference between these two syntaxes but the common practice is to use curly brackets when you have only one line of code in your block and do-end on other cases.
When using Ruby methods and the different libraries, you will notice that a lot of methods retrieve blocks and execute them. In such a case, the block will be added to the method call at the end, after you pass all the other parameters. For example, the next code is totally legit:
my_method("some string param") do
puts "Inside a block!"
end
Blocks can receive parameters as well. To specify the parameters, just write their names between vertical bars after the do keyword or after the opening curly brackets:
my_method("value...") do |param1, param2, param3|
puts param1 + param2 + param3
end
my_method("value...") { |param1, param2, param3| puts param1 + param2 + param3 }
There are more types of code containers in Ruby like lambdas and procs and you will want to use them in slightly different scenarios. Anyway, I’m not going to discuss them here because they are not as common as blocks (but it is recommended you read a bit about them and know what they mean).
Methods
Methods are basically blocks with names… I guess this is a bit of a very generic definition but it’s generally what it is. The way to define a method is by using the def keyword, then the name of the method (method names in Ruby should start with a lowercase letter), then its parameters (if any), then the code and end at the end:
def method_name(param1, param2)
# something
end
A method can be declared inside a class or outside it. In case you define it outside of a class, it will be available from anywhere within your code. When a method is declared inside a class, it is available only via a class instance (for instance methods) or the class object (for class methods).
Method Return Value
Any method returns a value in Ruby. You do not need to use any keyword (like return in C#) to return a value – the last statement return value will be returned to the caller.
For example, the next method will return 1:
def always_returns_1
1
end
Additionally, you can use the return keyword to explicitly return a value. When the return keyword is used, it acts like in C# and also exits the method. For example, the next sample method always returns 1:
def always_returns_1
return 1
return 2
end
Calling Methods
Executing a method is very straight forward – just write its name and it will run. You should also specify parameters (if any) and pay attention here – parenthesis is optional.
For example, the next sample demonstrates the different method calls available:
def add(a, b)
a + b
end
result1 = add(1, 2)
result2 = add 1, 2
Be careful when using parenthesis – the opening bracket must come exactly after the method name without any space. This means that add(1, 2) and add (1, 2) are not the same!
Classes
A class is an object that gathers methods, properties and variables that together generate a single logical unit, just like C# classes. The difference between C# classes and Ruby classes is that in Ruby, a class inherits from the Class object (which eventually is an Object object) and in C#, a class inherits directly from Object.
To define a class you start with the class keyword followed by the name of the class, which must start with an uppercase letter. For example, the next sample defines an empty class named EmptyClass:
class EmptyClass
# Everything goes here
end
Instance Methods
To create instance methods, you just add method definitions inside the class definition (between the class name and the end keyword):
class MyClass
def my_method
# something
end
# more methods...
end
Constructor
Sometimes you need to run some initialization code when the class is created. This is done via a constructor method and in Ruby, the constructor is defined in a method named initialize.
For example, the next class will print “Hello there” when it is created:
class HelloClass
def initialize
puts "Hello there"
end
end
Notice that a constructor method can retrieve parameters just like any other method. To do that, just specify parameters for the initialize method.
Class Methods
Class methods are like static methods in C# – they are methods which can be invoked without creating an instance of the class. To create a class method, use the self keyword before the name of the method. For example, instead of say_hello, name the method self.say_hello:
class MyClass
def self.say_hello
puts "Hello"
end
end
Instance/Class Variables
Apart from methods, classes can contain variables. There are two kinds of variables:
- Instance variables – they are instance-specific and are available to instance methods.
- Class variables – they are shared between all instances of the class and are available to all methods of the class (both instance and class methods). Similar to static variables in C#.
Instance variables are declared with an at sign (@) in front of them. For example - @first_name. Class variables are declared with two at signs (@@) in front of them. For example – @@instance_counter.
This is very simple and I think the next list will make it even clearer:
- first_name – local variable (available in the current scope only).
- @first_name – instance variable (available in the current instance only).
- @@first_name – class variable (available in all class instances).
Creating Class Instances
To create a class instance we use the new method on the class. This is a built-in behavior, just like the new keyword in C#. Calling the new method will eventually execute the class’ constructor (the initialize method).
For example, the next code contains a simple class definition with a constructor and afterwards I create an instance of the class:
class Hello
def initialize
puts "Hello"
end
end
# Init the class
hello = Hello.new # prints "Hello"
If the initialize method contains parameters, you will need to pass them on the new call.
After the class instance exists, you can execute its instance methods using a dot. For example, the next sample contains a class definition and a method call afterwards:
class Hello
def say_hello
puts "Hello"
end
end
hello = Hello.new
hello.say_hello # prints "Hello"
To execute class methods you don’t need to initialize a class instance and you just use the class name instead of the class instance:
class Hello
def self.say_hello
puts "Hello"
end
end
Hello.say_hello
Using Code from Other Files
As your application grows, you will probably want to separate your code into several files to ease maintenance. Moreover, you will probably want to use Ruby libraries or even load .NET assemblies (with IronRuby). To do so, Ruby provides a method named require which retrieves the name of the file you want to load.
For example, the next sample will load a Ruby file named mylibrary.rb:
You can also specify the full path to the file.
After you load a file with the require method, all the classes, methods, variables, whatever that exist in this file will be available in the current file (similar to the Add Reference concept in .NET).
[Loading .NET assemblies with IronRuby are done the same way but I will talk about it on the next post.]
Conclusion
Well, 15 minutes have passed and now you know all the basics of the Ruby language. You can now go to a Ruby restaurant and ask the waitress for a delicious meal with no worries.
That is all you need to get started. That’s all. But if you like it, I do recommend you to learn more because Ruby have so much more to offer.
Stay tuned… the next post in this series will teach you all you need to know about IronRuby.
All the best,
Shay.
P.S. If you think something is missing from here, I need to clarify subjects, I need to delete it all or anything else, please let me know.
- Posted by Shay Friedman on June 22, 2010
I’ve just uploaded the slides from my recent sessions at the Epicenter and NDC conferences. They appear on the presentation page as well.
NDC 2010 – Riding IronRuby on Rails (Norway, June 2010)
Abstract: The most famous Ruby–driven framework is, by far, Ruby on Rails. With IronRuby, .NET developers can now take advantage of this incredible web framework without leaving their comfort zone. In this session, Shay Friedman will build an entire Web 2.0 site from scratch while using and explaining the key features of Ruby on Rails.
Come and see what Ruby on Rails is all about and what's made it the success it is today.
You can also watch the session video – streaming, iPod video (320x240), MPEG-4 for QuickTime (1280x480)
NDC 2010 – Practical IronRuby (Norway, June 2010)
Abstract: Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. IronRuby version 1.0 has recently been released, unleashing the power of Ruby to the .NET world.
In this session you will get familiar with the Ruby language and its amazing ecosystem and you will learn to take advantage of it in your everyday development tasks.
Come and see how this great new addition to the .NET family makes your development process faster, clearer and happier!
You can also watch the session video – streaming, iPod video (320x240), MPEG-4 for QuickTime (1280x480)
Epicenter 2010 – Ruby on Rails Vs. ASP.NET MVC (Ireland, June 2010)
Abstract: 2010 is the year when two great web development frameworks arrive at the .NET world – ASP.NET MVC 2.0 and Ruby on Rails (via IronRuby). It is the time to get to know these frameworks and learn their advantages and disadvantages. In this session I will walk you through the good, the bad and the ugly of both frameworks providing you points to consider when coming to choose one of them.
Come and see how these two wonderful web development frameworks collide!
Epicenter 2010 – ASP.NET MVC (Ireland, June 2010)
Abstract: Since the early days of ASP and later on ASP.NET, web development has always been a confusing experience. Several different architectures were suggested over the years, all of them struggled with the same goal – to make the code clear, clean and easily maintainable. Eventually, Microsoft took up the glove and created the framework that would change web development in Microsoft environment forever – ASP.NET MVC.
In this session Shay Friedman will take you on a journey to explore the different capabilities of ASP.NET MVC 2.0 by building an entire web application from scratch. Come and see the future of web development in the .NET world!
Epicenter 2010 – Practical IronRuby (Ireland, June 2010)
Abstract: Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. IronRuby version 1.0 has recently been released, unleashing the power of Ruby to the .NET world.
In this session you will get familiar with the Ruby language and its amazing ecosystem and you will learn to take advantage of it in your everyday development tasks.
Come and see how this great new addition to the .NET family makes your development process faster, clearer and happier!
Enjoy!
Shay.
- Posted by Shay Friedman on June 22, 2010
The last two weeks have been really fascinating for me. I flew 6 different flights, took 4 trains, did a total of 5 sessions in 2 conferences, lost one suitcase and got it after two days, and met numerous amazing people.
So let’s start from the beginning. My first stop was Dublin, where the Epicenter conference took place. The agenda covered various different programming languages like .NET, Java, Ruby and even Smalltalk. I did three talks – Practical IronRuby, ASP.NET MVC and Ruby on Rails Vs. ASP.NET MVC. Apart from these talks I got to participate in a web frameworks panel where I talked about ASP.NET MVC. The other panelists were Peter Ledbrook that talked about Grails, Jamie Van Dyke who talked about Ruby on Rails, Julian Fitzell who talked about Seaside and Matt Raible who talked about Java web frameworks:
The great thing in this conference for me was that I got to hear, for the first time, about the worlds outside the Microsoft world. It was a really interesting experience for me, and I’m sure it will be the same for every .NET dev out there (highly recommended!).
Apart from that, I hanged out with a lot of cool people – thanks everybody for the great time!
After the conference was over I stayed in Dublin for a few more days mainly for sightseeing… On one of the days I took a trip to Glendalough which was spectacular! Ireland is soooooo beautiful!!!!
Afterwards I moved on to the second part of my tour – the Norwegian Developer Conference. I took a flight to Oslo, Norway got a train to the central station and walked to the hotel (great location!)… A few minutes after I get to the room in Oslo I get a Twitter message to call Anders (one of the organizers). He asked me to replace Scott Bellware as the first talk on the day after since Bellware had done a very Bellware-like thing and missed his flight. Luckily I had my talk ready by that time so everything went really good. Eventually I had two talks – Practical IronRuby and Riding IronRuby on Rails.
So the conference, I must admit, exceeded all of my expectations – the organization was flawless (kudos to the organizers), I got to meet and talk with tons of awesome smart people, I talked in front of a lot of people and I learned so much about technology, about drinking a lot of beer and about sides of Microsoft which I’ve never thought about (thanks Scott, Rob and Seb!). It was a great experience for me and I wish any one of you to go through something like that.
One of the peeks of the conference for me however, came right after it ended… During the conference I tried, with the help of Tim Heuer, to run a simple IronRuby console on a Windows Phone 7 device. We faced some problems with the version Tim had so we kinda let it go with no success. But! Tim didn’t despair and contacted Tomas from the IronRuby team. Tomas found the problem and hacked a fix very quickly… so while I was sitting in my room just before leaving for the airport, I got this picture from Tim:
It ran! IronRuby console on a real Windows Phone 7 device! soooooooo cool!!!!!
So… Thanks all for the great time! I was really glad to meet each and every one of you and I hope to meet you all again sometime!
Shay.
P.S. The slides of the talks and links to the videos will be published soon.