IronRuby via C# Series


12
Aug 08

Learning Ruby via IronRuby and C# Part 7

Click here to view the entire IronRuby via C# series

In the last part of this series we talked about hashes in Ruby and C# and we saw how they are very close in functionality. In this entry we are going to start looking at the parts of Ruby that do not easily translate directly into C#. In a few past posts you have seen some parts of Ruby that vary a bit from C#, but in most cases the languages are still very similar. You will now start to see the features that people brag about when they tout Ruby’s power over most statically typed languages.

The first feature that we are going to look at is called “duck typing”. It is really less of a feature and more an underlying principle of the language. “Duck typing” refers to the way in which objects are used polymorphically in Ruby. In C# an object’s class is its type and it represents the mechanism through which object can be manipulated. So, in C#, if you wanted to interact with a class then you need to know its type, one its base types or an interface supported by the type. So, lets define a tiny hierarchy here:

public abstract class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public abstract int VacationDays { get; }
}

public class Manager: Employee
{
    public override int VacationDays
    {
        get
        {
            return 25;
        }
    }
}

public class Developer: Employee
{
    public override int VacationDays
    {
        get
        {
            return 18;
        }
    }
}

In this you can see that we have a Employee class with Developer and Manager child classes. If we wanted a method to be able to operate on either a Manager or a Developer then we would create a method that used our Employee base class like this:

public void PrintEmployeeVacation(Employee employee)
{
    Console.WriteLine("Vacation Days: {0}", employee.VacationDays);
}

And now we could pass either a Manager or Employee in and we would print out their vacation. So, how would we do this in Ruby? Well, in Ruby this hierarchy would look like this:

class Employee
    attr_accessor :first_name
    attr_accessor :last_name
end

class Manager < Employee
    def vacation_days
        25
    end
end

class Developer < Employee
    def vacation_days
        18
    end
end

But if we created the same method then we would create it to look like this:

def PrintEmployeeVacation(employee)
    puts "#{employee.vacation_days}"
end

So, that looks very similar to the C# method, but there aren’t any types. So how does that work? If we aren’t specifying any types, how does Ruby know that it is valid to call “vacation_days” method on the object? This is where Ruby’s duck typing comes in. Since in Ruby a class is not its type, Ruby simply relies on whether or not a class has an implementation of a particular method. Which is why it is called “duck typing”, because “if it walks like a duck, and talks like a duck, then it must be a duck”!

And since Ruby doesn’t rely on anything other than the fact that a class supports a particular method, we see that there is nothing regarding the “vacation_days” method in the “Employee” class at all. Ruby has no concept of an abstract class or method. And guess what, that means that these classes don’t need to share a base class! In fact, Ruby has no concept of interfaces, and so you don’t need one of those either. So, we could define these classes like this:

class Manager
    attr_accessor :first_name
    attr_accessor :last_name    
    
    def vacation_days
        25
    end
end

class Developer    
    def vacation_days
        18
    end
end

Notice that there is no first name and last name in the Developer class. I took those out so you can see that they don’t share a base class and they don’t even have an identical implementation. Ruby just doesn’t care. It doesn’t matter to the “PrintEmployeeVacation” method because it only uses the “vacation_days” method. This means that any class which has a method called “vacation_days” which returns a value that can be used in the “puts” method will work in this method. This means that we could change the Developer class to this:

class Developer    
    def vacation_days
        "18"
    end
end

And it would still work. Since the string “18″ is valid in the context of our method, then execution would occur as normal. How is that for flexibility?

But all of this flexibility also comes at a cost. In fact, most of you who are used to static languages may be sitting there with your mouth agape in horror. You are probably thinking “you can pass anything into that method, and if the ‘vacation_days” method isn’t supported then it will just blow up!”. What about if an object is passed in that has the method which doesn’t perform the same operation, or return a valid result, or takes parameters? Well, you will get a runtime error. Because of that you may be shaking your static head and saying, “but how would you ever control the behavior!?”

The answer is unit testing. In dynamic languages, just like in static languages, everything should be unit tested. Sure the programmer must to have better knowledge of what an object needs in order to be passed into a particular method, but the lack of compile time checking is one of the fundamentals of dynamic programming. It is not a weakness, it is a feature! If the thought of not having every parameter on every method checked for type makes you lose sleep, then dynamic languages may not be for you. The important thing is that you must use heavy testing in order to flush out these errors and keep your code quality high.

I hope you enjoyed this look at the power and flexibility of Ruby’s duck typing, in a future post we are going to delve a bit more deeply into Ruby’s type system by introducing you to modules in Ruby. Have fun!


3
Aug 08

Learning Ruby via IronRuby and C# Part 6

Click here to view the entire IronRuby via C# series

Welcome back for part 6 in my learning Ruby via C# series. In the last entry we discussed arrays in Ruby and C#. We saw how Ruby arrays were actually more like Lists or Collections in C#. They are able to be modified, appended, resized, searched, sorted, etc… In this entry we are going to discuss an equally powerful data structure, the hash or associative array. The hash is close to the Dictionary or Hashtable classes in C#. We are going to use the Dictionary class in this entry since it is the more often used class.

So, in C# if we wanted to declare a Dictionary and populate it with a few keys and values we would do something like this:

var jobs = new Dictionary<string, string>();
jobs.Add("Developer", "Jimmy Dean");
jobs.Add("Senior Developer", "John Smith");
jobs.Add("Network Engineer", "Bob Franklin");

In Ruby hashes are a first class member of the language, so they have their own syntax for declaring them. One way to declare a hash looks like this:

jobs = {}
jobs["Developer"] = "Jimmy Dean"
jobs["Senior Developer"] = "John Smith"
jobs["Network Engineer"] = "Bob Franklin"

But you could also do it all in one line by separating the key and the value with the “=>” operator:

jobs = {"Developer" => "Jimmy Dean", "Senior Developer" => "John Smith", "Network Engineer" => "Bob Franklin"}

Sweet. But in Ruby, symbols are the preferred way of representing the keys in hashes. It would be similar to defining an enumeration in C# and using that for the Dictionary key:

public enum Jobs
{
    Developer = 1,
    SeniorDeveloper = 2,
    NetworkEngineer = 3
}

var jobs = new Dictionary<Jobs, string>();
jobs.Add(Jobs.Developer, "Jimmy Dean");
jobs.Add(Jobs.SeniorDeveloper, "John Smith");
jobs.Add(Jobs.NetworkEngineer, "Bob Franklin");

In Ruby we would set it up like this:

jobs = {}
jobs[:Developer] = "Jimmy Dean"
jobs[:SeniorDeveloper] = "John Smith"
jobs[:NetworkEngineer] = "Bob Franklin"

So now that we know how to build up our hashes, how do we get our entries back out? We probably know how to do this in C#:

Console.WriteLine(jobs[Jobs.Developer]);

That would send “Jimmy Dean” out to the console. Since we know how to do it in C#, we already know how to do it in Ruby!

puts jobs[:Developer]

Very cool. Ruby hashes also support the “each” method just like the Ruby array. In C#, we would loop through each item in the dictionary like this:

foreach (KeyValuePair<Jobs, string> job in jobs)
{
    Console.WriteLine(String.Format("{0} {1}", job.Key, job.Value));
}

We could also cheat and use my “Each” extension method that I defined:

public static void Each<T>(this IEnumerable<T> list, Action<T> func)
{
    foreach (T item in list)
    {
        func(item);
    }
}

And then our C# code looks like this:

jobs.Each(j => Console.WriteLine(String.Format("{0} {1}", j.Key, j.Value)));

Looks better and pretty much what our Ruby version looks like:

jobs.each { |key, value| puts "#{key} #{value}" }

So now we have seen how to build up, access, and then iterate through our hashes. But what is the coolest use for hashes in Ruby? Well, we mentioned it in an earlier post, and that is method parameters! It allows us to have a variable number of named parameters. As C# developers we are not used to having named parameters, but if you think about it, if you name parameters then their order is not important. So, if you pass hashes for parameters then you can change method signatures without worrying about breaking older code. Lets look at a method real quick:

def print_names(params = {})
    first_name = params.fetch(:first_name, "John")
    last_name = params.fetch(:last_name, "Doe")
    job = params.fetch(:job, "No Job")
    
    puts "#{first_name} #{last_name} Job: #{job}"
end

You can see that we are pulling our variables out of the hash that is passed into the method, providing default values. The default value is the second parameter of the “fetch” method. So, we could call this method like this:

print_names(:first_name => "Justin", :last_name => "Etheredge", :job => "Programmer")

Or like this:

print_names(:job => "Programmer", :last_name => "Etheredge", :first_name => "Justin")

Or this:

print_names(:first_name => "Justin", :job => "Programmer")

Or even like this:

print_names

Are you starting to see the flexibility of this method of parameter passing? If later on we need to add a parameter for number of years in position:

def print_names(params = {})
    first_name = params.fetch(:first_name, "John")
    last_name = params.fetch(:last_name, "Doe")
    job = params.fetch(:job, "No Job")
    number_of_years = params.fetch(:number_of_years, 0)
    
    puts "#{first_name} #{last_name} Job: #{job} Number of years: #{number_of_years}"
end

All of our old code will still work. Now this isn’t all ponies and gumdrops though, you can see that it makes calling methods much longer affairs. It also doesn’t help that our method’s only parameter is “params = {}”. That doesn’t exactly provide us anywhere to start for calling the method. You have to look into the method to see what you need to pass, and here you see that we are fetching the values up front and putting them into local variables. But what if the method was long and didn’t do this up front? Then you might have references to the hash strewn all throughout your method and you would have to hunt for them. The only other option is to have good documentation for your methods, which obviously won’t always happen. Suffice to say, that this can make a method very hard to call in the hands of a poor programmer, but then again, Ruby is all about giving sharp tools to sharp people.

Another flexibility that this gives you is the ability to do different things based on which items are in the hash. Since Ruby does not support method overloading, it makes it hard to have multiple methods perform different functions based on their parameters. With hashes though you can check if certain items exist in the hash using the “has_key?” method and then perform different actions based on what is passed.

As you have seen, hashes are incredibly useful data structures in Ruby. When you combine them with methods they can give you flexibility that most languages just don’t have. There are many more things you can do with the Ruby hash, but you’ll have to go check out the Ruby hash docs yourself.

I hope that you have found this little tutorial helpful!


28
Jul 08

Learning Ruby via IronRuby and C# Part 5

Click here to view the entire IronRuby via C# series

Welcome back for part 5 in my learning Ruby via C# series. In this post I want to cover hashes (or associative arrays) and arrays in Ruby. These two data structures are used quite often in Ruby, and so we are going to spend a little bit of time going over them. But first I want to clear up some mistakes that I made in the first post of the series. In the first post I had explained what attribute accessors were and I showed a class that looked like this:

class Person  
    attr_accessor :count  
    @@count2 = 0  
  
    def count2  
        @@count2  
    end  
  
    def count2(value)  
        @@count2 = value  
    end  
end

Well, that isn’t exactly correct. Well, I was trying to show static variables in Ruby and I wanted to show the static version of “attr_accessor”. The first item I wanted to clear up is that I used instance method in this class because we had yet to cover static methods. This was done on purpose, but I wanted to show it as static now. The second thing is that you can do this in a shortened manner using the cattr_accessor method. The “c” stands for “class” since Ruby calls these “class variables and methods” and not “static”. The only problem is that this is part of ActiveSupport and not the standard Ruby libraries. ActiveSupport is a library of helper methods for Ruby on Rails, and currently has some issues running under IronRuby so I am not going to use it for now.

The second thing that I wanted to clear up, which actually was a mistake, is that the two “count2″ methods are not what is defined. The second “count2″ method should have an “=” between the word “count2″ and the “(” that starts the argument list. So, if we don’t use the “cattr_accessor” method, our class (using static methods) will look like this:

class Person  
    attr_accessor :count  
    @@count2 = 0  
  
    def self.count2  
        @@count2  
    end  
  
    def self.count2=(value)  
        @@count2 = value  
    end  
end

And then we could access these new static methods like this:

Person.count2 = 123
puts Person.count2

Phew, now we can finally get to the new stuff! Let’s first talk about arrays. An array in Ruby is essentially the same as an array in C#. Lets say we wanted to declare an array of integers in C#:

int[] numberArray = { 1, 2, 3, 4, 5 };

Okay, now lets do the same thing in Ruby:

number_array = [1, 2, 3, 4, 5]

You can see that Ruby lets us define an array simply using square brackets and assigning the value to a variable. Now, while a C# array is immutable (meaning we can’t modify it) a Ruby array can be modified. So, in C# in order to add the number “6″ to our array above we would have to do this:

int[] numberArray2 = new int[numberArray.Length + 1];
Array.Copy(numberArray, numberArray2, numberArray.Length);
numberArray2[numberArray2.Length - 1] = 6;

But in Ruby, we could simply do this:

number_array << 6

This uses the “<<” operator, therefore making Ruby arrays more similar to a C# collection than a C# array. In fact, Ruby arrays has methods for deletion and insertion. If we were to say:

number_array.delete(3)

Then when we output the array, we would get “[1,2,4,5]“. This is important because Ruby arrays are 0 based, just like C#. So, the “delete” method removes the item “3″, not the index (in fact, if there were more than one “3″, it would remove all of them). We would have to use the method “delete_at” in order to remove an item at an index:

number_array.delete_at(3)

We can also insert into the array using “insert” (the first parameter is the index, the second is the value):

number_array.insert(2,4)

So, what if we wanted to add an item to the end (without the “<<” operator):

number_array.push(7)

Okay, so we have a push method, what about pop? Of course, in Ruby you can use arrays just like stacks!

number_array.pop

Like I said before, in Ruby arrays are zero based, just like C#. They even use the same method to access the items. In C#:

int value = numberArray[0];

In Ruby:

value = number_array[0]

But what if we just wanted to see the last item in the array, but not remove it? In C# we would have to use the length of the array minus one:

int value = numberArray[numberArray.Length - 1];

But in Ruby, you can access arrays using negative indexes:

value = number_array[-1]

Negative arrays are indexed from the end of the array. How cool is that? Another cool thing you can do is use ranges to access an array:

number_array[0..2]

This would return “[1,2,3]“. As you can see, the Ruby array is very flexible.

So, enough about accessing arrays, what if we want to do some operations on these arrays. Lets add up all of the items in C#:

int total = 0;
foreach (int i in numberArray)
{
    total += i;
}
Console.WriteLine(total);

And what about in Ruby?

total = 0
number_array.each do |i|
    total += i
end
puts total

Lets do it more efficiently in C# using the LINQ aggregate method (if haven’t seen Aggregate (also called Fold) you can see an implementation and explanation here):

int total = numberArray.Aggregate((accumulator, i) => accumulator + i);
Console.WriteLine(total);

And then we will do it in Ruby using inject:

total = number_array.inject(0) { |accumulator, i| accumulator + i }
puts total

Sweet. You can really see how far C# has come to closing the gap in C# 3.0 with Linq. Before C# 3.0 and Linq we would be losing quite a bit of expressiveness here. Again, we can use the “select” method in C# and the “map” method in Ruby to transform items in an array. If we wanted to multiply each item in our array by 2, we could do this in C#:

var result = numberArray.Select(i => i * 2);

In Ruby we could do it like this:

number_array.map { |i| i * 2 }

Phew, I think we have had about enough with Arrays in Ruby. There is so many things that Ruby arrays can do, and we just don’t have the space to cover all of it. Go check out the Ruby docs if you want to see all of it.

Well, I was going to discuss hashes, but I think that arrays went on for a lot longer than I had originally planned. This seems to be a recurring theme, but there is just so much to talk about! I hope that you enjoyed the post and in the next one we are going to start talking about hashes.


25
Jul 08

Learning Ruby via IronRuby and C# Part 4

Click here to view the entire IronRuby via C# series

In my previous post on learning Ruby via Iron Ruby and C# we left off with a little bit about loops in Ruby and how the classic looping constructs are rarely used in Ruby. I showed you that in Ruby you can do a simple “for” loop like this:

for number in 1..10  
    puts number  
end

But in Ruby you are more likely to do it like this (although this would probably still be fairly rare):

(1..10).each do |num|
    puts num
end

And as I mentioned, you can do this in C#:

foreach (int i in Enumerable.Range(1,10)){
    Console.WriteLine(i);
}

Most people don’t know that ranges exist in C#. That is probably because it was just added in .net 3.5. As you can see, it is part of the library. Not a good or bad thing, just something to point out. Ruby ranges are a bit different, and quite a bit more flexible. In Ruby the “1..10″ creates a range from 1 to 10, and then “1…10″ creates a range from 1 to 9. Very subtle, and I’m sure it has been the source of at least a few bugs. :)

One problem with C# ranges is that the first number is the start, and the last number is the count. Not the start and end numbers. The distinction is subtle, but important. In C# if we do this:

foreach (int i in Enumerable.Range(-5,-1)){
    Console.WriteLine(i);
}

We will get an ArgumentOutOfRange exception. What would we get with Ruby if we did this:

(-5..-1).each do |num|
    puts num
end

Well, we would get the numbers -5, -4, -3, -2, and -1 printed out! If we wanted to do this in C#, we would have to do this:

foreach (int i in Enumerable.Range(-5, 5))
{
    Console.WriteLine(i);
}

In my mind (and I’m a C# programmer) the Ruby one makes more sense! They both work, I just think the Ruby one reads easier. Ruby ranges also support a step method that allows us to make ranges that don’t increment by 1:

(1..10).step(2) do |num|
    puts num
end

In C#, we could do this:

foreach (int i in Enumerable.Range(1,10).Where(x => (x + 1) % 2 == 0))
{
    Console.WriteLine(i);
}

We could also just define our own “Step” extension method, which would probably make life easier for us.

Another cool part about Ruby ranges is that you don’t have to use numbers:

("a".."z").each do |char|
    puts char
end

And yes, this prints out the letters from “a” to “z” as a range. What happens when we do this:

("aaa".."bbb").each do |char|
    puts char
end

Yep, we get every permutation from “aaa” to “bbb”, such as aab, aac, aad, aae, etc… All 704 of them. I know there is 704 because I did this:

puts ("aaa".."bbb").to_a.length

Sweet. “to_a” puts the range into an array. Then “.length” just returns the length of that array. Ranges in Ruby really are flexible and powerful, in fact, there is even more that you can do with them that we aren’t even going to cover here. Just to whet your appetite though, Ruby can actually construct objects using ranges. It requires a bit more knowledge that we have covered so far, but you can actually do something like “Person.new(“aaa”)..Person.new(“bbb”)” and construct all of the objects for every permutation.

One thing to note though is that C# ranges are implemented using deferred execution. Therefore, you can get a range from 0 to Int32.MaxValue and if you call “.Take(10)” on it, then the first 10 numbers will be generated. The rest of the list will never be created. Ruby also does this with ranges, which means that you can do things like this:

infinity = 1.0/0        
infinite_range = (1..infinity)                
infinite_range.each do |num|
    if (num > 15)
        break
    end
    puts num            
end

If Ruby was not implementing this in a delayed fashion, then we might get an error from this. :) Ruby has a representation of “infinity” that it uses to store numbers which are too large or small for it to deal with. Here we are getting a reference to infinity by using 1.0/0. We could have also done something like “10**10**10″ which is 10 to the power of 10 to the power of 10. Once we have our infinity representation we can use it as the end of the our range. Then we can Range.each passing in each number until we pass 15, in which case we break. Only the numbers 1 to 15 are ever created. This allows us to pass a range into another method and then let that method decide how many items it is going to pull off the list.

In C# we could simply do a range using “Enumerable.Range(1..Int32.MaxValue)” since the Range method is bounded by the length of Int32 anyways. Ruby on the other hand is capable of storing extremely large numbers. And I mean extremely large numbers. If you don’t believe me, do 10000**10000 and look at how many zeros you are going to get (** is the exponential operator)! And yes, that is ten thousand to the power of ten thousand.

Well, it appears that my tour of Ruby ranges went on a bit longer than anticipated. So I am going to end it there for the evening, and next time I am going to finally get into Ruby arrays and hashes. I hope you enjoyed!


24
Jul 08

Learning Ruby via IronRuby and C# Part 3

Click here to view the entire IronRuby via C# series

In the previous part of my series about learning Ruby using C# we discussed constructors, instance methods, parameters, and then touched on blocks a bit at the end. Well, in this post we are going to delve a bit further into classes by talking about static methods (class methods in Ruby) , a bit more info about parameters, and then finish it up with some tidbits about conditionals and loops.

To start it off, lets look at some quick static methods in our Person class. Lets say we want to define a method that returns the total count of Person objects that have been instantiated. In C#, our class would look like this (notice that I have left out the rest of the class for brevity):

public class Person
{
    private static int instanceCount = 0;
    
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName)
    {            
        this.FirstName = firstName;
        this.LastName = lastName;
        instanceCount++;
    }    

    public static int InstanceCount()
    {
        return instanceCount;
    }
}

So, as you see, we just have a static variable named instanceCount that tracks the number of instances created. We then have a static number that allows us to retrieve this number. In Ruby we actually have several ways to define a method like this. One is to use “self” and one other (there are several) is to use the class name (in our case “Person”). We are going to use “self” in our example, but you can just replace that with the class name if you like:

class Person
    @@instance_count = 0
    
    attr_accessor :first_name
    attr_accessor :last_name
    
    def initialize(first_name, last_name)
        self.first_name = first_name
        self.last_name = last_name
        @@instance_count += 1
    end
    
    def self.instance_count
        return @@instance_count
    end
end

Here you will notice the static variable from the previous post, and we have our corresponding static method. Pretty cool, huh? Looks extremely similar to C# so far. You would consume this just as you would in C#:

puts Person.instance_count

Okay, so we discussed static methods, and now I have a few more quick things that I want to show you about parameter passing in Ruby. The first thing is that Ruby supports default parameters! I have always wanted default paramters in C#, and I have heard all of the arguments about just using overloads, and I just don’t buy it. I want me some default variables, and I want them now! So, in Ruby if I wanted to default the parameters in my constructor, I could just do this:

def initialize(first_name = "John", last_name = "Doe")
    self.first_name = first_name
    self.last_name = last_name
    @@instance_count += 1
end

So great! Now, I can call the “new” method without any parameters and it will default one or both parameter values for me. So doing this…

person = Person.new
puts person.first_and_last_name

Results in “John Doe” being written to the console. In order to get the same effect with C#, we’d have to define three constructors:

public Person(): this("John", "Doe") { }
public Person(string firstName) : this(firstName, "Doe") { }
public Person(string firstName, string lastName)
{            
    this.FirstName = firstName;
    this.LastName = lastName;
    instanceCount++;
}

Not too terrible, but defaults would have been nice!

Now, there is one other thing that Ruby does with parameters and that is to allow hashes to be passed as parameter lists. Since we have yet to discuss hashes, I am going to skip this for now, but we will come back to it later on!

Lets take a look at a boolean in Ruby. In C# we just declare our boolean like this:

bool isValid = false;

And in Ruby, since types are implicit, we would just do this:

is_valid = true

So, what about an if statement? In C#, our if statement would look like this:

if (isValid){
    //do something
}

And our Ruby if would look almost the same:

if (is_valid)
    #do something
end

But Ruby supports the unless statement… unless?

unless (is_valid)
    #do something
end

Yep, unless. It is the negation of “if”. This would run the code block only if “is_valid” is false (aka not true). We would just do this in C# (which also works in Ruby):

if (!isValid){
    //do something
}

But the fun doesn’t stop there! Ruby also less us put the “if” and “unless” statements at the end of a line! For example, I could do this:

puts "It is valid!" if is_valid

Very interesting. It now reads almost like an English sentence, and does it exactly what it sounds like. It writes out “It is valid!” if “is_valid” is true. We can also do the same with “unless”:

puts "It is not valid!" unless is_valid

Pretty sweet. So now that you have seen these statements, you can also be aware that Ruby supports pretty much all of the normal boolean operators that C# does, and so I’m not going to go through them one by one. We will use them in our next section though.

On with the loops! Ruby supports many different looping mechanisms like “while”, “until”, “do..while”, “do..until”, and “for”. A C# for loop that looks like this:

for (int i = 1; i <= 10; i++){
    Console.WriteLine(i);
}

Would look like this in Ruby:

for number in 1..10
    puts number
end

The biggest difference is that in Ruby, these classic looping constructs are almost never used! I’m not even going to bother going through them! In Ruby the idea that you most often see is that objects themselves should be responsible for their own looping. This is evident in the use of the “each” method.

You have probably seen C#’s “foreach” statement quite a bit:

foreach (string name in names){
    Console.WriteLine(name);
}

Ruby has a similar construct:

names.each do |name|
    puts name
end

But if you combine that with Ruby’s excellent support for ranges (yes, C# has a Range class as well, Ruby’s is just easier to use) then you can do the above for loop like this:

(1..10).each do |num|
    puts num
end

And that is the way that you will see it done quite a bit. In fact, if you had done “(1…10)” then it does 1 to 10 exclusive (meaning only 1 to 9). Since we are starting at 1, you could also write it like this:

10.times do |num|
    puts num + 1
end

We had to add in the “+ 1″ since the “times” method starts at 0. But it does execute it 10 times. Again, we are starting to see a recurring pattern with Ruby. And that pattern is that there are 18 million ways to do everything! If you don’t like choice, then Ruby may not be the language for you!

And there you have it folks. I am going to quit there for now and let you soak it all up. We have covered some static methods, default parameter goodness, boolean madness, and finally a little bit of looping. In the next post I’ll talk a bit more about Ranges, and then delve into the hash tables (or associative arrays) that we mentioned earlier. I will also discuss arrays in Ruby and why they are different from C# arrays.

I hope you enjoyed the post, and please let me know if there is anything that you have questions about or would like to see!