Why Rails? Part 3: Ruby 8

Posted by jeff Thursday, December 22, 2005 01:46:00 GMT

Ruby is sweet. So sweet I call it my programming candy. And it’s another big reason I’m switching to Rails from ASP.NET.

If you’re not familiar with Ruby yet, I know even the name “Ruby” might make think it’s a toy language. It doesn’t sound “technical enough”. It might even sound like one of those crazy scripting languages you’ve heard about that only seem to run on Unix machines and have even stranger names (Tcl, Perl, Awk, Python).

Ok, yes, it’s a scripting language, and yes, its heritage comes more from the Unix/Linux side of the planet than our own. But it’s far from “crazy”, and it’s not just for people using one of those free ”’nix” operating systems. Ruby is in fact the only fully object-oriented scripting language I know. It’s being used in very “technical” places like ThoughtWorks and IBM.

If it sounds strange to use a scripting language to build websites, remember that ASP was a scripting language and plenty of world-renowned companies still use it today to run their websites. “But ASP.NET is not a scripting language anymore! It’s a full OO language! I can write interfaces! I can write classes!” you cry.

So I probably need to say it again: Ruby is a fully object-oriented programming language. Anything you can do in C# or Java or C++ – inheritance, polymorphism, and encapsulation – are all 100% there in Ruby.

Except it gets better: it’s a scripting language that is strongly typed. No, you don’t declare types – that would be a staticly-typed language. But types are dynamic. You can add or remove methods and properties and behaviors to types or to instances of those types. You don’t have to declare variable types because they’re inferred correctly from the context.

If you’re still reading this and still doubting that anything reasonable can come from this kind of programming language, stick with me for just two more minutes.

Imagine you’re an ASP.NET developer using C# or VB.Net (which you probably are). You love C# (which you probably do) or VB.Net. But face it. Most of your website is data-driven, as most business-class web apps are these days. Every app you write needs C# code that usually talks to a data layer, which in turn talks to stored procedures, which in turn talk to the raw tables in your database. The only time you use the real strengths of C# is if you have a non-trivial middle tier impementing business logic (you are following a good MVC model, aren’t you?).

Now suppose I asked you to write a base class we can use for all of your web apps that would automatically read a database table and emit C# code to let do the usual CRUD on those tables.

In other words, I want to declare a class like this:

class CustomerTable : public TableBase

and I want TableBase to be able to add methods and properties to my class automatically. So if there’s a column called “CustomerID” in my table, I want a .CustomerID property in my class as if I had defined it explicitly. Oh, and I want a method called .FindByCustomerID().

That would be really hard to do in C#. I mean, really, really hard. Ok, I mean impossible.

In Ruby, it’s easy. The base class can define those methods in my derived class on the fly. So it simply reads the table schema and adds the necessary properties and methods. So my client code gets really, really nice. Easy to read and easy to write.

Rails does exactly this. The base class we decided was impossible to write in C# is called ActiveRecord in Rails:

class Customer < ActiveRecord::Base

and voila, my Customer class has methods like .find_by_customer_id() and a property called .customer_id. This kind of mapping from objects to the relational model just eliminated, oh, about 50% of the ASP.NET coding I used to do.

But I digress – this is not an article about Rails per se, but about Ruby.

There’s a big debate about static vs. dynamic languages, and I still like to use staticly-typed languages for all of my desktop-application work. But for web development, scripting languages have always been better and Ruby is, to me, the king of all scripting languages when it comes to website development.

What else about Ruby has made me switch?

Well, I’ve had experiences similar to Martin Fowler: the Ruby community has been great to me and lots of other people. Check out the Ruby and Rails mailing lists to get started.

Writing Ruby code is just nicer. There are neat conventions like suffixing a method name with ! when the method will change the internal state of an object and ? when you’re asking it a yes/no question (“returns a bool”, we would say in C#).

Reflection is so much easier than it is in C#: String.instance_methods gives you all the messages you can send (in C# we would say “methods you can call”) to a String object. Find out if an object can receive a message you want to send it (again, in C#, we would say “if an object has a method you want to call”) by using obj.responds_to?(method_name).

And by golly, it’s just more fun. It’s so much less code to write for the equivalent C# functionality. Ruby statements sound more like english sentences. I spend much more time thinking about the problem i’m solving and much less time scanning the intellisense dropdown lists figuring out which method I need to call next.

Space is running short. Let me conclude with just a couple of small examples to tease you into exploring Ruby.

Title case a string in C#:

    string myString = "wAr aNd pEaCe";
    TextInfo myTI = new CultureInfo("en-US",false).TextInfo;
    Console.WriteLine(myTI.ToTitleCase( myString)));</p>

and now in Ruby:

    "wAr aNd pEaCe".titlecase

Write a function to return two values in C#:

    void GetFirstAndLast(string fullname, out first, out last)
    {
        string[] parts = fullname.Split();
            first = parts[0];
            last = parts[parts.Length -1];
    }

    string first;
    string last;
    GetFirstAndLast("Donald P. Duck", out first, out last);

and now in Ruby:

    def get_first_and_last(fullname)
        parts = fullname.split.values_at(0, -1)
    end

    first, last = get_first_and_last("Donald P. Duck")

So you ASP.NET developers out there who think I’m crazy, please tell me why. And you Ruby gurus out there who can provide even better examples, please provide some more!

As for me, I gotta get back to my candy.

Comments

Leave a response

  1. Marc   December 22, 2005 @ 03:30 PM

    "It might even sound like one of those crazy scripting languages you've heard about that only seem to run on Unix machines and have even stranger names (Tcl, Perl, Awk, Python)."

    Ruby is a simplification and improvement of the Perl language, the name Ruby is even considered a tribute to Perl. So by that definition Ruby is also a crazy scripting language, no?

    Sems a little condascending to me, implying that Microsoft (ASP.Net) developers - the target audience of this blog - think of Perl, Python etc as "crazy scripting languages that only seem to run on Unix"

    I was expecting an article about Ruby vs C# but got more about how Rails simplifies web app development.

    An ok article, but room for improvement

    I realise I am being harsh here but I believe this site is onto something good. If not then I would simply ignore it and move on.

  2. Jeff   December 22, 2005 @ 08:03 PM

    Hi Marc,

    Thanks for your contents. I thought it would be apparent that the term "crazy" was tongue-in-cheek. (I even say that Ruby is not "crazy".) So I'm not sure why it came off as condescending; it certainly wasn't indended that way.

    Most .Net developers are not familiar with Perl or Ruby or Python, and have very preconceived notions of what they are. The 'nix world seemed very foreign to me for a long time, as I suspect it is for a lot of .Net developers out there.

    As for why I mention Rails in the article, this article is part of a series entitled "Why Rails?". So it was only appropriate that I touch on why Ruby gives Rails its power. That's the entire idea behind the article.

    Hope this helps. Thanks a lot for taking the time to write and I welcome your input anytime.

  3. Composition Rfp   April 28, 2006 @ 02:53 AM

    Gonna have to give it a try :)

  4. Outdoor Duplicate Chaise Lounge   April 28, 2006 @ 11:30 PM

    But I'm not sure why :)

  5. Sanction Delhi Development   April 29, 2006 @ 02:28 PM

    Thanks for the write-up...

  6. George   October 16, 2006 @ 02:18 AM

    what about a sum algorithim that excepts any type of number, in one function

    class Enumerable
      def sum
        self.inject {|t,c| t+c}
      end
    end
    

    this does two things it alouse any collection to do this it will also join lists of strings. blocks are a lot like lambdas it alows you to write loops.

  7. kino   May 24, 2008 @ 01:14 AM

    In the study of time, the Transcendental Deduction, for example, can never furnish a true and demonstrated science, because, like the Ideal, it is what first gives rise to inductive principles.

  8. Ellroy   May 30, 2008 @ 11:23 PM

    As will easily be shown in the next section, the Ideal of human reason, on the contrary, exists in the objects in space and time.

Comment