1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

What's New in Ruby 1.9.1?-- Dot Syntax Changes

By

One of my favorite changes in Ruby 1.9.1 is a relatively small one. Newlines are now allowed before or after the dot (method call) operator. This seems like a relatively small change, but it allows for a very expressive syntax for long chains of method calls.

For example, the following method call chain will parse an IP address, boolean and its bits with a network mask and re-create an ASCII IP address.

mask = "255.255.224.0".split(/\./).map{|d| d.to_i }
ip = "192.168.203.45".split(/\./).each_with_index.map{|d,i| (d.to_i&mask) }.join('.')

puts ip

With more than a few method calls on a single line, especially ones involving blocks, regular expressions or in this case, the unpack method, it's a very confusing line. Breaking each logical step up into a line is a big help. This could have been done in Ruby 1.8, but being able to put the dot on the next line next to the method call is much more clean.

Here is the same code rewritten for Ruby 1.9, isn't it much easier to read?

mask = "255.255.224.0"
  .split(/\./)
  .map{|d| d.to_i }

ip = "192.168.203.45"
  .split(/\./)
  .each_with_index
  .map{|d,i|
   (d.to_i&mask)
  }.join('.')

puts ip
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. New in Ruby 1.9.x
  6. Method Call Syntax Changes

©2014 About.com. All rights reserved.