Monday, December 22, 2008

Block-tastic

I am in the process of reading "The Little Book of Ruby" by Huw Collingbourne. I have found some very cool tricks that you can do in ruby, such as:

def sample
return 1, "new" <- return multiple data types
end

This also lends itself to arrays with multiple data types. Such as:

a = [1,sample,"hello"] <- which is [1,[1,"new"],"hello"] as I just learned

The each loop is very nice, similar to the foreach loop in c#.
Instead of:

foreach(int x in intlist)
{
Console.Writeline(x);
}

it is:

intlist.each do
|x|
Puts(x)
end

Another cool thing is the alternate syntax for delimiting blocks ie.

Given the each list above, the following is acceptable:

intlist.each{
|x|
Puts(x)
}

but remember to include either do or { on the same line as the each method, or (as i found out) it will throw an error.

Very cool stuff.
More observations to follow... Enjoy!

No comments:

Post a Comment