Wrapping up my trip to Japan – TechEd and RubyKaigi

A few days ago I got back from Japan, where I gave 2 talks – one at TechEd Japan and one at RubyKaigi. Honestly, it was a breathtaking experience for me.

First of all, Japan… it’s so different! someone even called it “an alternate universe”. Japanese people are so kind and so well-behaved. And everything is clean. Sooooo freaking clean!!!! I must recommend you to visit Japan if you haven’t don’t it already. It is an experience you wouldn’t want to miss.

Secondly, I had a unique opportunity to speak both at a Microsoft and a Ruby conferences at the same week and see the different audience. They’re all developers and yet they are so different! Microsofties are the responsible grown ups and Rubyists are the rebellious teenagers. It was amazing to see the differences. Anyway, I had a blast in both conferences and met some outstanding people!

Before I move to the content of my talks, I’d like to personally thank Shozo Arai for having me at TechEd and helping me with my RubyKaigi talk and to thank Ayumu Aizawa for having me at RubyKaigi. You people rock!

And to the content of my talks (I’ll add them to the presentations page soon too)… The first one was TechEd:

TechEd Japan 2010

The conference took place at the Yokohama Conference Center and I gotta say – Yokohama is a beautiful place. For instance, this was the view from my hotel room:

Yokohoma from my hotel room

During the conference I also played Microsoft Kinect for the first time, which was AWESOME. I want one. If you wanna buy me one, please do.
In addition, I participated in a special MVPs launch (Japan has 200 MVPs!) where I was introduced to everyone. It was very cool and I got to meet some exciting people there.

Anyway… I also had a session there named “Let’s Dynamic – IronRuby and the .NET Framework” (that’s my translation to the Japanese name :-) ). It was the first time for me to have a translator. I had to stop every 1-2 sentences and let him translate. It was quite an experience! but I had fun and the audience seemed interested too :-)

These are the slides:

If you’re interested in one of the demos, please let me know and I’ll upload them. I’m just too lazy to do that now :-) I know the session was recorded on video too. I guess you’ll be able to view it on the conference site - http://www.microsoft.com/japan/teched/2010/.

From TechEd I moved to RubyKaigi, which took place at Tsukuba (2 hour train drive away from Yokohama):

RubyKaigi 2010 It was the first Ruby conference for me so I had to understand what was going on first. They had these cool whiteboards where you could write various things. For example, your favorite method and favorite programming language (C# made it to the list!). Click on the picture to view in a bigger size:

RubyKaigi Favorites WhiteboardThey also had a huge map of the world and everyone wrote where they came from. I was the only one from Israel:

RubyKaigi map of the world During the party of the first night I also got to meet some famous people (famous at least for Ruby developers!) like Matz (the creator of the Ruby language) and Chad Fowler (author of “The Passionate Programmer” and one of the organizers of RubyConf) as well as other awesome people.

Anyway, I had a session here too! Its name was “IronRuby – What’s in it for Rubyists?” and its goal was to show Rubyists how they can take advantage of IronRuby and different .NET frameworks like WPF, Silverlight and others.

These are the slides:

Again, If you’re interested in one of the demos, please let me know and I’ll upload them.
The session was recorded as well and can be found at http://rubykaigi.tdiary.net.

In conclusion, I had a blast!!! Japan is an incredible country and the conferences were outstanding! Hopefully I’ll get to visit there again in the future.

Arigato!
Shay.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

My MSDN Magazine article is out – IronRuby on Windows Phone 7

The new MSDN Magazine issue, the one of September 2010, features my article about taking advantage of IronRuby on Windows Phone 7:
”IronRuby expert Shay Friedman goes mobile and shows you how to build a Windows Phone 7 app with Microsoft’s implementation of the popular Ruby dynamic language.”.

You can read it on the printed version or online - http://msdn.microsoft.com/en-us/magazine/ff960707.aspx.

Enjoy!
Shay.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Keep your Chin Up Child and Wipe the Tears from your Eyes

Last week was hysterical. It started with a flight to Nashville and a 3-day conference, Devlink, with 2 IronRuby sessions on the last day I had to do. On the second day of the conference I had a nice talk with Michael Moores, who turned out to be working with Micahel Letterle who is the first IronRuby MVP. That was the closest I’ve ever got to another IronRuby MVP :)

Anyway, the thing is that in the end of the second day just before I started the last dry-runs for my talks, I saw Jimmy Schementi’s blog post, “Start spreading the news”: the future of Jimmy and IronRuby, where he was announcing the he was leaving Microsoft, mainly because his boss had asked him “what else would you want to work on other than Ruby”. That leaved IronRuby with one developer (Tomas) and one partial-time tester that helps in other stuff too (Jim). They are both very talented, but still – 1.5 (or even less) people who work on a product kind of gives you the idea of where this is going to. IronPython is not in a better position either by the way.

The news hit me, I gotta say, by total surprise. I didn’t see it coming (at least not so soon) and my first reaction, like most reactions on the Twitter-sphere, was an “oh no, the evil monster has done it again” reaction. It’s a very natural psychological reaction to disappointment:

“The psychological results of disappointment vary greatly among individuals; while some recover quickly, others mire in frustration or blame or become depressed.”
-- "Disappointment", Wikipedia

And indeed, I was frustrated (not depressed, though; technology isn’t worth to be depressed over it) by the fact that something I believed in, with all my heart, was starting to die. And I didn’t believe in it because I thought it was cool (even though it is cool), but because I thought it added value. And that’s what it’s all about right there.

Getting back to the timeline, on the next day I had 2 sessions about IronRuby and I decided not to let the news affect them. However, I did do a little small talk with the audience before every session about it. The reactions varied from “I couldn’t care less” reactions to “I don’t know” to frustration. And watching other people being frustrated by that was a huge push for me to keep doing what I do. Moreover, the news spread so fast that as I was walking that day in the halls of Lipscomb University, I could hear people talking about the subject. I think I overheard about 5 different conversations about IronRuby that day.

Add to that the tons of reactions on Twitter, the conversation on the IronRuby mailing list and the various emails I’ve received since then (of people saying they were planning to use IronRuby and what do they do now) and you get one meaning - people care.

And solely because of that, I believe that IronRuby has a future. With or without Microsoft. Honestly, I’d hate to see it being released from Microsoft since this was a wonderful way to get it inside medium-large corporations that still require the Microsoft “stamp”. However, I won’t place my bet on that to continue.

To tell you the truth, I’ll understand Microsoft if they decide to stop funding the project. Think about it, Microsoft’s first and foremost goal is to make money. Just like your or my company. And they’re currently making money from various things:

  • Licenses for Windows, Office, Visual Studio, SQL Server and other products.
  • Professional support.
  • Hardware.
  • Training.
  • Certification exams.
  • Other stuff I don’t know about.

The biggest part of Microsoft’s revenues comes from selling licenses. As .NET developers, we are a part of Microsoft’s revenues system – we use Windows, we code in Visual Studio, we use Windows servers because that’s what we know and when we need a DB we directly go with SQL Server because it integrates perfectly with Visual Studio and other Microsoft products we have. By that I answer reactions I’ve seen like “if this is how Microsoft treats its open-source projects, we can’t trust it to continue with ASP.NET MVC too” – ASP.NET MVC will not die. Ever. Just because it follows all the preconditions. However, IronRuby does not – you do not use Visual Studio, you don’t have to use Windows, SQL Server is not so widely used with Ruby frameworks. And it gets even worst – you might be tempted to open the door and leave; to join your Ruby friends on the other side, the ones who write code in Mac and deploy their apps to, God helps us all, *nix machines.

In other words, CRAZY. The guy who approved that must have been drunk or something.

BUT, there was some rationality in the decision of writing a Ruby implementation on top of the .NET framework too – to give options, to make the framework better. In other words, to add value. And you know what, it might have had the power to even, God forbid, make these lunatic Ruby guys to show some interest in the .NET framework.

And you know what happens when money and making the product better are on the same scale? they burn the scale and the “making the product better” side up and run away with the money. That’s not Microsoft, that’s life.

So what does the future hold for us, IronRubyists? Well, I’ve got no idea. The current situation is kinda hazy – not here and not there. On the one hand, Microsoft is still controlling the code contributions, web site, github account and other related resources. On the other hand, they cut in human resources for the project.
My prediction is that Microsoft will give up IronRuby (and IronPython) in the next few months. As I said, if I was a director in Microsoft – I wouldn’t be able to justify its existence (but I would have so much more money too so I can’t really tell what I would have done :) ). And ones this happens, it will create a huge opportunity for the IronRuby community.

Since IronRuby is open source, the community will be able to take control and continue developing IronRuby. This will allow us to advance faster (hopefully) and more importantly, work on the features we want instead of the features we’re told we want. From the stuff I’ve been hearing and reading, the community of IronRuby is bigger than I though and people are willing to help. Along with the help of well-known icons like Rob Conery, Jimmy Schementi and others we can get to large audience and get even more people on board.

However, in order for this to happen I think that a few things should happen:

  • Microsoft must declare that the IronRuby project is not funded anymore and by that, it ceases to exist internally inside Microsoft.
  • Microsoft must pass the control over the entire code base, web site, github account, codeplex page, copyrights and all other related things to the community.
  • A single guy (or gal!) or a tiny team should become responsible for IronRuby. More people can be responsible for parts of the project but one or a very small amount of people should be responsible for all of it.
  • A roadmap should be written to allow people to start working.
  • Finding a contact point inside Microsoft is important too, IMHO. Someone who can help with DLR issues (the DLR is still being developed inside Microsoft) or other issues we might run into.

In conclusion, if you’re asking me, IronRuby is here to stay. It’s become stronger than Microsoft and the next months/years will be our time to prove it. Personally, I know I won’t stop working with it, talking about it and helping you guys with your questions about it. I’ll do it because I believe in it and papa always told me to do what I believe in.

“we are not alone, we feel an unseen love
we are sons and heirs of grace
we are children of a light that never dims
a love that never dies, keep your chin up child
and wipe the tears from your eyes”
-- from Music Box by Thrice

Shay.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

IronRuby and IronPython on the next Israeli .NET User Group Meeting

August is going to be a very busy month for me, speaking at DevLink, TechEd Japan and RubyKaigi. In addition, with the help of Dror Helper, we’re bringing dynamic languages to the local .NET crowd in Israel!

When?

August 18th, 17:30-20:30.

Where?

The Israeli .NET User Group (IDNUG) August meeting,
Microsoft offices, Dekel room
HaPnina 2, floor 0
Raanana, ISRAEL

What?

17:30 - 18:00   Assembly
18:00 - 19:15   “Introduction to IronRuby”
                           Shay Friedman
19:15 - 19:30   Break
19:30 – 20:30  “Introduction to IronPython”
                           Dror Helper

Abstract #1: Introduction to IronRuby
Ruby has been a home for some great innovative frameworks like Ruby on Rails, Cucumber and Rake. IronRuby 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.

Abstract #2: Introduction to IronPython
Do you want to learn about dynamic languages and their uses? IronPython is a good place to start. This dynamic .NET language can be used to develop just about anything – windows application, web services and Silverlight to name a few. This session will explain what Python is all about and how to write .NET applications using IronPython. The session is intended for .NET developers without any previous knowledge of Python that want to learn about the power of Dynamic Languages.

How?

Register now at https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032456794&culture=he-IL

See you all there!
Shay.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Using the IronRuby Interactive Console

Hi all,

Eric Nelson, an Evangelist in Microsoft UK, has published a guest post of mine in his successful blog. The post explains how to take advantage of the IronRuby interactive console to explore .NET assemblies.

You can find the post here: http://geekswithblogs.net/iupdateable/archive/2010/07/26/guest-post-using-an-interactive-console-to-explore-the-.net.aspx.

Enjoy!
Shay.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

A Chat with me on the IronLanguages Podcast

IronLanguages

Recently I had the chance to chat about IronRuby in an episode of the IronLanguages podcast.

The episode is now available at http://ironlanguages.net/epidsode-2-chat-with-shay-ironshay-friedman.

All the best,
Shay.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

IronRuby is going to Japan!

If you don’t already know, Japan is where the Ruby language was created, back in 1995. This is the origin of this great language, this is where it all started!

So I’m very excited to announce that on this August, IronRuby is coming to Japan!

IronRuby in Japan

I’m going to visit Japan in August and talk about IronRuby! I will participate in two very different conferences – TechEd Japan and RubyKaigi.

TechEd Japan, the main Japanese .NET conference, will take place between August 25th to August 27th. I’m going to speak on day 2 of the conference (the 26th) about IronRuby for .NET developers.

TechEd Japan 2010 

RubyKaigi 2010 will take place between August 27th to August 29th. It is a world-class Ruby conference that hosts Ruby great minds from all over the world like Yukihiro Matsumoto (the creator of Ruby), Yehuda Katz, Jeremy Kemper and others. I’m going to give there a talk on the 29th, named “IronRuby – What’s in it for Rubyists?”.

RubyKaigi 2010

I’m so excited to visit Japan and present in front of both .NET and Ruby developers. Maybe this will be the bridge between the large Japanese Ruby community and the large Japanese .NET community!

Shay Friedman – bridging between developers since 1983!

See you there!
Shay.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Working with .NET Lowercase Namespaces and Classes in IronRuby

[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.

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.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Starting Using IronRuby in 25 Minutes

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:

Running IronRuby Files

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.

kick it on DotNetKicks.com Shout it



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Learning Ruby in 15 Minutes

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:

a = a + 1 if a > 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:

require '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.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

Sponsers