Call me crazy, but this is why I classify myself as a language geek. When I learn something fascinating, i wonder hmm how can I do that with X language? My last post I did an example of the Builder pattern as described in Effective Java by Joshua Bloch. The main motivation for me to use Builder is to have flexible parameter lists, without worrying about order of parameters (there are a few other reasons outlined in the book, but this is what I find cool).

Its too easy.

My class:

RUBY:
  1. class Address
  2.   attr_accessor :street, :street2, :city, :state, :zip, :address_type
  3.  
  4.   def initialize(&block)
  5.    
  6.     #set default values
  7.     self.city = "Chicago"
  8.     self.state = "IL"
  9.    
  10.     #set value from block
  11.     instance_eval &block if block_given?
  12.  
  13.   end
  14.  
  15. end

And the usage of it:

RUBY:
  1. def testDefaultValues
  2.     myaddress = Address.new
  3.     assert_equal("Chicago", myaddress.city)
  4.     assert_equal("IL", myaddress.state)
  5.   end
  6.  
  7.   def testStreetStateZip
  8.     myaddress = Address.new do
  9.       self.street = "this is the street"
  10.       self.zip = "11111"
  11.     end
  12.     assert_equal("Chicago", myaddress.city)
  13.     assert_equal("IL", myaddress.state)
  14.     assert_equal("this is the street", myaddress.street)
  15.     assert_equal("11111", myaddress.zip)
  16.   end

Wow, huh? Compare to

JAVA:
  1. public void testBuilderDefaults() {
  2. Address expected = new Address.Builder("Chicago", "IL").build();
  3. assertEquals("State is IL", "IL", expected.getState());
  4. assertEquals("City is Chicago", "Chicago", expected.getCity());
  5. }

then the optional params are chained to that:

JAVA:
  1. public void testBuilderStreetStateZip() {
  2.    Address expected = new Address.Builder("Chicago", "IL").street("this is an address").zip("11111").build();
  3.   assertEquals("this is an address", expected.getStreet());
  4.   assertEquals("11111", expected.getZip());
  5.   assertEquals("IL", expected.getState());
  6.   assertEquals("Chicago", expected.getCity());
  7. }

Full source for Ruby (though I was able to paste it all here!)
Address class in ruby | Address test in ruby

And for Java, if you want to compare ...
Address class in Java | Address test in java

Yes... sometimes its hard not to gloat. :-D

yeah yeah yeah, its not really "fair" to compare strongly typed languages... but as I said, my motivation is to have easy parameter lists without having to remember specific ordering of params for constructor or use multiple set methods.