Save development time and effort with Ruby

No readers like this yet.
Two different paths to different outcomes

Opensource.com

The workday is winding down. You and your significant other have a dinner reservation, so you're eager to get home. And that's when the email arrives.

"I need to include one more report in my meeting with the execs tomorrow," it says. "I've attached some spreadsheets. Can you write me something to calculate the [irrelevant, obscure business term]?"

You start thinking about what you'll need to get this done. If you only know a compiled language like C# or Java, the list probably goes something like this:

  • Create a new project folder.
  • Create a source file.
  • Come up with a class name (even though you're going to throw it away later).
  • Type out a class definition (or have your IDE do it for you).
  • Write your code.
  • Compile your code.
  • Run your code.

...And that's assuming you get it right on the first try and don't have to revise, re-compile, and re-run it a few times. Right about now, you're probably thinking you'll have to cancel dinner.

But if you happen to know an interpreted language like Ruby, the list is much shorter:

  • Create a source file.
  • Write your code.
  • Run your code.

You don't need a project folder, because there are no compiled class files to keep track of (just your source file). You don't need a class name or definition, because Ruby lets you write code outside of a class if you want. You might have to revise and re-test a few times, but there won't be a compilation step between each attempt. There's just less... ceremony. And it means your simple task will get done quicker.

Get started quick: "Hello, world"

Even in a simple "Hello, world" program, you can see the difference. Here's how the code might look in C#:

public class Hello
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, World");
   }
}

Compare that with a Ruby program to do the same thing:

puts "Hello, World"

That's right, just the one line! No class definition, no methods, just the code you need.

I don't want to imply that you can't create classes and objects in Ruby; in fact, that's the way most Ruby code is written. But you aren't forced to use that style for simple problems. The language gets out of your way and lets you code how you want.

Accessors

Here's another common operation that's easier in Ruby: attribute accessors. It's widely accepted as best practice not to access an object's instance variables from outside the class directly. Instead, you set up accessor methods to help ensure proper encapsulation. (In fact, unlike most object-oriented languages, Ruby doesn't allow you to access instance variables directly. It's just safer that way.)

If we had a Person class with a name instance variable, we'd need to set up one method to read the value of name and another method to write it. Here's how that code would look in Java:


public class Person {
    // Set up an instance variable.
    private String name;

    // Set up a reader method.
    public String getName() {
       return name;
    }

    // Set up a writer method.
    public void setName(String name) {
       this.name = name;
    }
}

Now, let's look at the Ruby version:


class Person
  # Set up reader and writer methods for @name.
  attr_accessor :name
end

When you call the attr_accessor method within a Ruby class's body, and pass it a symbol (that's the :name) with the attribute you want to create, it will automatically set up a reader method, a writer method, and an instance variable for you—all with a single line of code.

Also, notice that while we had to declare a type (String) for the instance variable and accessor methods in the Java example, we didn't have to in Ruby. That's because unlike many compiled languages, Ruby doesn't do type checking. Ruby simply trusts that you know what type of object is stored in a given variable, and will only call methods appropriate for that object. (If you don't, you'll get an error at runtime. But in practice, this doesn't happen very often.)

These are small conveniences, but imagine how much coding they'll save you across a large project!

Open source benefits

Ruby is released under an open source license—one that allows use within proprietary software. This carries a wide variety of benefits, of course. The most tangible, though, is that it can be downloaded, compiled, and installed on any server where it's needed, automatically, any time, for free.

Ruby's community strongly prefers open source licenses for the libraries they release, too. Thousands of libraries covering a wide variety of tasks are ready for use in your project. Installation is automatic as well, thanks to the RubyGems packaging system.

Here are a few more examples of how Ruby speeds development:

  • Want to compose several strings together into one? In Java or C#, you'll probably need to create a separate instance of the StringBuilder class. In Ruby, the methods you need are right there on the string object.
  • Want to see if a string matches a regular expression? In most other languages, regular expressions aren't first-class citizens. You have to create a string with the pattern you want, then compile the pattern into a regular expression object and, finally, compare that object against the original string. Ruby can do it in just one step; you just create a regular expression using /a regex literal/ and use the =~ operator to match it against your string.
  • In most object-oriented languages, the only way to share code between multiple classes is inheritance, and you can only inherit from a single class. If an object needs behavior from several other classes, you have to either compose that object out of several other objects, or duplicate methods from those other classes in the object's class. In Ruby, though, you have mixins, which let you mix methods from several different modules into a class. (A mixin is a collection of methods, like a class, except you can't create instances of it.) This offers all the benefits of multiple inheritance (like in C++), but none of the added complexity.
  • Mocking objects for unit tests in other languages requires either either creating a subclass specifically to use in the test, or using a third-party mocking framework. In Ruby, you can simply redefine the method directly on the object.

I could go on, but I think you get the point. The creators of Ruby expended a lot of effort to make almost every aspect of the language simple and concise. Coding in Ruby is just more pleasant and productive.

Don't get me wrong, the formality of other languages can have its benefits. Take type checking, for example: sure, it's a pain to have to declare the class of every variable and method. But languages that do type checking can spot more errors in your code at compile time than Ruby can. Static typing also allows for compiler optimizations that make completed applications run faster.

But in practice, I find the benefits of coding in Ruby far outweigh the costs. Having a solid unit test suite (which Ruby makes easy to write) tends to catch all the same errors that type checking would. And Ruby's flexibility makes code simple to refactor and maintain.

If your development time is precious to you, and you want to maximize what you can accomplish in that time, you should give Ruby a try. But be careful: once you switch, you may never want to go back!

User profile image.
Jay is the author of Head First Ruby (O'Reilly, 2015). He has been an avid Ruby user for nearly a decade, and frequently speaks about the language at conferences and user groups. He's been working in online developer education since 2011.

4 Comments

In C++ all I have to do is :

#include

int main() {
std::cout<<"hello world"
}

I do agree there are some cases in which Ruby or other similar languages can speed up your development time but most of the time I find I'm spending the time with the design of the code not the implementation.
The article gives examples of one time through away code. Sure, for that a scripting language is the best solution but when performance matters and your code is running for thousands of times on a server then in my opinion the performance penalties of scripting languages ( which are really huge vs. compiled languages ) start to hit you.

On the other hand, if you knew a nice mix of procedural languages and object oriented languages and a selection of compiled, interpreted and scripting languages, you could just think about the problem and choose the best tool for the job.

I don't mean to imply that Ruby might not be the right tool for the example job as it doesn't happen to be one of the tools in my personal toolbox but if you "only know a compiled language like C# or Java"... really, what -are- you doing claiming to be a developer?

Not sure about C#, but in Java, not having a hash literal syntax makes it way slower to use this stand-in for a proper class that you don't really want to have to write for just one or two places in your code.

Also, considering the high-level reporting problem specifically for Ruby apps running on Rails, there is even less overhead than the "make a file, write code, run it" steps you described in my work. I typically handle these in an interactive Ruby shell ("rails console") where I can type a line of code and see the result of running it just by hitting Enter. My entire domain model is at my fingertips. Active record's query syntax pair with Ruby's higher-order functions like "map", "group_by", and "select" to make a lot of reporting needs doable in this interactive shell. If I outgrow the amount of code that's easy to edit in one line, I assign that result to a temporary variable and continue. When I'm done, I might keep a copy the code for future reference.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.