Java to Ruby Cheat Sheet

Introduction

Following my posts on the joyful transition from the Java world to the Ruby world, and due to (sort of) popular demand (may be in a quite specific segment, still), here is a quick tentative of an equivalence between the two worlds. If you’re a daytime Java, nighttime Ruby developer, this may interest you.

English: Official Ruby logo Русский: Официальн...

English: Official Ruby logo (Photo credit: Wikipedia)

This is by design a rather broad sweep, with neither pretension or intention of completeness. Also, even if this is a sort of Map (well, a Hash), some of the items are more equivalent than identical. In other words, they are tools or techniques that I use for the same purpose, even if they can differ widely in what they do.

When adequate, I added some explanations about the reasons of the pairing.

Language

Map → Hash
The Hash is Ruby equivalent of a Map. But at the same time, it is much much more: it is each rubyist Swiss Knife, able to serve many purposes from a simple core. The Hash is one of the two most abused collections of Ruby, the other being the Array (note that a good part of their behaviour is actually common, being included from the all-powerful Enumerable module). Both the Hash and the Array have literals ({} and [] respectively), even if there can be some good reasons to use Hash.new.

 
A Symbol is what you will use in place of a constant (when used as a name – constants also exist in ) or an Enum value. No compile check or autocompletion here, just an interned String with a guarantee that each usage will always refer to the same object. Symbols are represented as colon-prefixed strings such as :name, and are the prefered key values in Hashes.

Duke, the Java Mascot, in the waving pose. Duk...

Duke, the Java Mascot (Photo credit: Wikipedia)

Constant → Symbol

static method → Class method
The (rightly) reviled static methods are aptly named “Class methods” in Ruby, as this is exactly what they are: methods defined not on an object but on a Class (which is of course also an object). Class methods are prefixed with “self”: self.a_class_method.

JavaBean → Hash
Java’s Struct is the JavaBean: a class with only getters and setters. Ruby standards frown upon made up classes, and in most situation you will seen just Hashes passed around. Note a nice alternative using Struct.

Getters and Setters → attr_accessor
Ruby has its own trick to “generate” getters and setters (well, methods named after an attribute, with an “=” for the assignation): you can simply add symbols after writing “attr_accessor”, and all accesses will work. Note that attr_accessor is no keyword nor part of the language: it is actually a simple Class method.

instanceof → respond_to
You do not check for types in Ruby (it is of course possible, but not advised – actually, if your Java code is full of “instanceof”, you may want to pause and reflect also), but instead look if an object talk like a duck. In place of asking for its instance, you may just ask if it “respond to” a given message. The type itself is irrelevant. It may seems like a casuist difference, but it is not: it is the kind of trick that allow you to have methods works on arrays, strings and files the same way, just using for example the << stream operator.

Tools

debugger → irb (rails c for rails) – or pry
While Ruby has a fully functional debuggers, I do not use it much. Missing an IDE is probably part of the explanation, but irb is certainly another. Irb, the Interactive Ruby Shell (not Bell, unfortunately) allows you to type Ruby statements and have them executed immediately. While no debugger per se, it covers most of the needs: execute step by step, inspect variable, change code on the fly. Rails console (‘rails c’ from the command line) gives you the same functionality while loading up all your Rails environment.

Pry is a more and more popular alternative to irb, featuring shell and documentation integration, and the option to be called in response to anything (like, an exception in the middle of a Rails application).

JUnit → Test/Unit or MiniTest (which are, by the way, the same thing)
Remember that JUnit is only the Java version of SUnit. Test/Unit or MiniTest now is Ruby default test engine, featuring the expect assertions and helper methods. An interesting aspect is that running any Ruby test class using the simple “ruby my_test.rb” actually execute the tests, due to a nice use of at_exit. Now that you are there, take a look at RSpec (or MiniTest/Spec), its more behavioral cousin.

Jacoco/Emma → Rcov/SimpleCov
What is a test framework without coverage? Rcov (for 1.8) or SimpleCov (for 1.9) give you the reports and a nicely formatted HTML page to compare your results. Good to see where your suite is lacking.

Eclipse → Sublime Text
This may looks like comparing Apples to Samsungs (or Oranges), but do not forget that with a dynamically typed language as Ruby, your IDE power is much more limited than in the green pastures of Java static typing. SublimeText offers a very nice editor and a good and growing set of plugins covering from Git integration to Ruby formatters. It is for pay, and worth every dollar of it. Try it for free, play around, and when it become your editor of choice, paying for value is something that should not be a problem.

Ant → Rake
So, we needed something equivalent to make in Ruby? Here is Rake, build as a very nice internal DSL. Rake is the one stop shop for every development task, running tests, starting jobs workers, or setting up database. Writing Rake tasks is simple and powerful, using just Ruby, which is a refreshing change from Ant XML.Icing on the cake : you declare dependencies between tasks using the ‘=>’ operator. No real overload here, just a clever use of… Hashes (I told you).

AOP → Aliasing
Something that can looks more alien to a lot of developers, you can obtain most of the AOP benefits in Ruby using aliasing: basically, you can rename a method (let say to “old_method_name”), then change the create one with the original name to do some work (like, start a transaction) then delegating to the  existing version. Rails does this kind of thing all over the place.

Dependencies

Jar → Gem
A Gem is a folder of source files with a minimalist organization (some kind of manifest and default directories for sources and tests). To avoid Gem hell, a gem can also declare its dependencies in both name and version.

pom.xml → Gemfile
The Gemfile is where you declare all gems that your application uses. While most people are used to it in Rails application, its mechanism is in no way linked to Rails, and actually a good way to organize the dependencies of any Ruby project.

Maven → Bundler
Bundler will read a Gemfile, and collect or download all the needed dependencies, creating a… Bundle. Beyond this simple use case, Bundler is full of options to refer to gem from local folders (very useful while extracting one) or Git repositories.

MavenCentral → RubyGems
The home of all public Gems, RubyGems is Ruby’s Maven Central: you can find everything there, and this is the place where Bundler will look up for your gems by default.

Web development (Rails biaised)

Servlet → Rails Controller
Base of any web development, the place where you receive Http request and return Http response is the Controller. For those using Spring MVC, it should be quite familiar.

web.xml → routes.rb
Routes are the place where you link your controllers with urls. Again, this is Ruby, so no XML but a small internal DSL. Take a good look at scope and namespace options once your application begin to grow.

JSP → erb
erb is Ruby default templating engine, allowing to embed Ruby in HTML page. The same principle exists for JavaScript (gasp). Take also note of Haml, which is quite popular in the Rails community.

DAO → Rails Model
Surprisingly enough, the DAO role is filled by Rails… model. Or more exactly by Class methods for finders (you to not call getAllPersons on a Person object) and instance methods for CRUD operations. This means that the Model and DAO are mixed in one single class, which has both good and ugly sides. Pick your poison, and alternative are possible.

Hibernate/JPA → ActiveRecord
With Rails having been heavily modularized, ActiveRecord is your all purpose ORM solution. Its evolution seems to mirror the one of Hibernate some year ago: initially a very simple but very constrained framework that worked under a solid serie of hypotheses on your model, it has now gained all sort of flexibility – at a price.

Author, Author !

James Gosling → Matz
Last but not least, Yukihiro “Matz” Matsumoto is Ruby benevolent dictator. His implementation of Ruby is the one of reference, and is affectionately named “MRI” (Matz Ruby Interpreter). By his own words, he created Ruby to “help every programmer in the world to be productive, and to enjoy programming, and to be happy.”. So far, this has worked for me.

Your turn now. What did I miss? Where do you disagree in my (obviously biased and personal) list?

Enhanced by Zemanta




6 thoughts on “Java to Ruby Cheat Sheet

    1. Martin Post author

      irb -> my_objects.methods ? Joke aside, RI / google works fine (I’ve found that googling “Ruby class method” works faster for me than looking in local documentation, and get the official API page to pop in first place most of the time)

      Reply
  1. stéphan

    Sorry not my last addendum ;)

    What about quality tools ?

    Emma/Clover → Code coverage : rcov
    Checkstyle → Cyclomatic complexity : saikuro or flog
    CPD → structural similarity : flay

    looks like metric_fu is combining the stack in a “lightweight” sonar

    for Sonar , I found this
    ruby plugin but doesn’t looks really active and complete

    What about continuous integration ?
    I found jenkins.rb
    Is there a lightweight one like inifinitest eclipse plugin ?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>