Ironruby.2 – Findamentals (Ruby with C#)

If you are going to write programs in Ironruby you need to learn to write programs in Ruby as Ironruby is DLR implementation to Ruby itself. So here are some of the fundamentals we need to understand before we start working on Rails, Silverlight and of course WPF.

Some of the basic programming things we need to understand here is to how to declare and use some variables and classes.

Variables:

Lets look at variables, if you have worked with C#3.0 var then you have a good head start. In ruby you do not declare variable types, what I mean by that is, you do not specifically say, I want to declare a integer variable X, instead you just assign a integer value to a variable and ruby infers the type based on the value assigned to it and treat the variable as such in the future. This is like using ‘var’ type in c# 3.0. The main difference between var and ruby declaration is that, in C#3.0 you have to prefix the variable with var type to make C# understand what type of value it is going to use. So much of talking and lets look at an example

We are going to declare a integer variable x and assign the initial value of 5 and then add 1 to it and then print the value of x and of course it will print 6. First lets look at it in C#. We are only looking at the meat of the code. You need to little bit more to make this one run in C# as you all know.

C#:

int x = 5;

x = x + 1;

Console.WriteLine(x)

Ruby:

x = 5;

x = x + 1;

puts x

as you can see there is no more ‘int’ declaration in it. lets fire up our rbx and see if it works. Please remember to use $ in front of the local variables so that it can carry over….

image

Class:

Now lets review how do we define a class and use it. For our discussion, lets say we create a class called Person with name, age, sex as the attributes and lets create a method called sayHello to introduce the person.

C#3.0: I would like to do this in 3.0 rather than 2.0 because of the 3.0’s new feature called object initializer. If we would be doing this in 2.0, I might end up writing bunch of lines.

class Person

{

public string Name {get; set;}

public int Age {get; set;}

public char Sex {get; set;}

public void sayHello()

{

Console.WriteLine(”Hello, My name is ” + Name “. Nice to meet you!”);

}

}

….

Person me = new Person();

me.Name = “rubyPerson”

me.sayHello()

….

Ruby:

class Person

attr_accessor :name, :age, :sex

def sayHello

puts “Hello, My name is ” + name + “. Nice to meet you!”

end

end

me = Person.new

me.name = “rubyPerson”

me.sayHello

but please remember when you use the iron ruby to use $ before the local variables…

image

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google

No Responses so far »

Comment RSS · TrackBack URI

Say your words

You must be logged in to post a comment.