|
| 1 | +--- |
| 2 | +layout: page |
| 3 | +title: To Ruby From Java |
| 4 | +--- |
| 5 | + |
| 6 | +Java is mature. It’s tested. And it’s fast (contrary to what the |
| 7 | +anti-Java crowd may still claim). It’s also quite verbose. Going from |
| 8 | +Java to Ruby, expect your code size to shrink down considerably. You can |
| 9 | +also expect it to take less time to knock together quick prototypes. |
| 10 | + |
| 11 | +### Similarities |
| 12 | + |
| 13 | +As with Java, in Ruby,... |
| 14 | + |
| 15 | +* Memory is managed for you via a garbage collector. |
| 16 | +* Objects are strongly typed. |
| 17 | +* There are public, private, and protected methods. |
| 18 | +* There are embedded doc tools (Ruby’s is called RDoc). The docs |
| 19 | + generated by rdoc look very similar to those generated by javadoc. |
| 20 | + |
| 21 | +### Differences |
| 22 | + |
| 23 | +Unlike Java, in Ruby,... |
| 24 | + |
| 25 | +* You don’t need to compile your code. You just run it directly. |
| 26 | +* There are several different popular third-party GUI toolkits. |
| 27 | + Ruby users can try [WxRuby][1], [FXRuby][2], [Ruby-GNOME2][3], or the |
| 28 | + bundled-in Ruby Tk for example. |
| 29 | +* You use the `end` keyword after defining things like classes, instead |
| 30 | + of having to put braces around blocks of code. |
| 31 | +* You have `require` instead of `import`. |
| 32 | +* All member variables are private. From the outside, you access |
| 33 | + everything via methods. |
| 34 | +* Parentheses in method calls are usually optional and often omitted. |
| 35 | +* Everything is an object, including numbers like 2 and 3.14159. |
| 36 | +* There’s no static type checking. |
| 37 | +* Variable names are just labels. They don’t have a type associated with |
| 38 | + them. |
| 39 | +* There are no type declarations. You just assign to new variable names |
| 40 | + as-needed and they just “spring up” (i.e. `a = [1,2,3]` rather than |
| 41 | + `int[] a = {1,2,3};`). |
| 42 | +* There’s no casting. Just call the methods. Your unit tests should tell |
| 43 | + you before you even run the code if you’re going to see an exception. |
| 44 | +* It’s `foo = Foo.new( "hi")` instead of `Foo foo = new Foo( "hi" )`. |
| 45 | +* The constructor is always named “initialize” instead of the name of |
| 46 | + the class. |
| 47 | +* You have “mixin’s” instead of interfaces. |
| 48 | +* YAML tends to be favored over XML. |
| 49 | +* It’s `nil` instead of `null`. |
| 50 | +* `==` and `equals()` are handled differently in Ruby. Use `==` when you |
| 51 | + want to test equivalence in Ruby (`equals()` is Java). Use `equal?()` |
| 52 | + when you want to know if two objects are the same (`==` in Java). |
| 53 | + |
| 54 | +[1]: http://wxruby.rubyforge.org/wiki/wiki.pl |
| 55 | +[2]: http://www.fxruby.org/ |
| 56 | +[3]: http://ruby-gnome2.sourceforge.jp/ |
0 commit comments