A Look at Ruby 2.1

ruby2.1_signal

In this article, we take a look at the spanking new features of Ruby 2.1. It was first announced by Matz at the Barcelona Ruby Conference (BaRuCo) 2013. We’ll be focusing on Ruby 2.1.0, which was released over the holiday.

Hopefully, by the end of the article, you’ll be very excited about Ruby 2.1!

Getting Ruby 2.1

The best way to learn and explore the various features is to follow along with the examples. To do that, you need to get yourself a copy of the latest Ruby 2.1:

If you are on rvm:

(You need to run rvm get head to get 2.1.0 final installed)

$ rvm get head
$ rvm install ruby-2.1.0
$ rvm use ruby-2.1.0

or if you are on rbenv:

$ rbenv install 2.1.0
$ rbenv rehash
$ rbenv shell 2.1.0

Note that for rbenv users, you probably want to do a rbenv shell --unset after you are done playing with the examples – unless you like to live on the the bleeding edge. Or you could simply just close the terminal window.

Let’s make sure that we are both using the same version:

$ ruby -v
ruby 2.1.0dev (2013-11-23 trunk 43807) [x86_64-darwin13.0]

So, What’s New?

Here is the list of features we’ll tackle today. For a more comprehensive list, take a look at the release notes for Ruby 2.1.0.

  1. Rational Number and Complex Number Literals
  2. def‘s return value
  3. Refinements
  4. Required Keyword Arguments
  5. Garbage Collector
  6. Object Allocation Tracing
  7. Exception#cause

1. Rational Number and Complex Number Literals

In previous versions of Ruby, it was a hassle to work with complex numbers:

% irb
irb(main):001:0> RUBY_VERSION
=> "2.0.0"
irb(main):002:0> Complex(2, 3)
=> (2+3i)
irb(main):003:0> (2+3i)
SyntaxError: (irb):3: syntax error, unexpected tIDENTIFIER, expecting ')'
(2+3i)
     ^
        from /usr/local/var/rbenv/versions/2.0.0-p247/bin/irb:12:in `<main>'

Now, with the introduction of the i suffix:

% irb
irb(main):001:0> RUBY_VERSION
=> "2.1.0"
irb(main):002:0> (2+3i)
=> (2+3i)
irb(main):003:0> (2+3i) + Complex(5, 4i)
=> (3+3i)

Working with rationals is also more pleasant. Previously, you had to use floats if you wanted to work with fractions or use the Rational class. The r suffix improves the situation by providing a shorthand for the Rational class.

Therefore, instead of:

irb(main):001:0> 2/3.0 + 5/4.0
=> 1.9166666666666665

We could write this instead:

irb(main):002:0> 2/3r + 5/4r
=> (23/12)

2. def‘s Return Value

In previous versions of Ruby, the return value of a method definition has always been nil:

% irb
irb(main):001:0> RUBY_VERSION
=> "2.0.0"
irb(main):002:0> def foo
irb(main):003:1> end
=> nil

In Ruby 2.1.0, method definitions return a symbol:

irb(main):001:0> RUBY_VERSION
=> "2.1.0"
irb(main):002:0> def foo
irb(main):003:1> end
=> :foo

How is this useful? So far, one of the use cases I’ve come across is how private methods are defined. I’ve always disliked the way Ruby defines private methods:

module Foo
  def public_method
  end

  private
    def a_private_method
    end
end

The problem I have with this is when classes get really long (despite our best intentions), it is sometimes easy to miss out that private keyword.

What is interesting is that private can take in a symbol:

module Foo
  def public_method
  end

  def some_other_method
  end

  private :some_other_method

  private
    def a_private_method
    end
end

Foo.private_instance_methods
=> [:some_other_method, :a_private_method]

Now, we can simply combine the fact that def returns a symbol and private takes in a symbol:

module Foo
  def public_method
  end

  private def some_other_method
  end

  private def a_private_method
  end
end

Foo.private_instance_methods
=> [:some_other_method, :a_private_method]

If you are interested in the implementation of this new feature, check out this blog post.

3. Refinements

Refinements are no longer experimental in Ruby 2.1. If you are new to refinements, it helps to compare it to monkey patching. In Ruby, all classes are open. This means that we can happily add methods to an existing class.

To appreciate the havoc this can cause, let’s redefine String#count (The original definition is here):

class String
  def count
    Float::INFINITY
  end
end

If you were to paste the above into irb, every string returns Infinity when count-ed:

irb(main):001:0> "I <3 Monkey Patching".count
=> Infinity

Refinements provide an alternate way to scope scope our modifications. Let’s make something slightly more useful:

module Permalinker
  refine String do
    def permalinkify
      downcase.split.join("-")
    end
  end
end

class Post
  using Permalinker

  def initialize(title)
    @title = title
  end

  def permalink
    @title.permalinkify
  end
end

First, we define a module, Permalinker that refines the String class with a new method. This method implements a cutting edge permalink algorithm.

In order to use our refinement, we simply add using Permalinker into our example Post class. After that, we could treat as if the String class has the permalinkify method.

Let’s see this in action:

irb(main):002:0> post = Post.new("Refinements are pretty awesome")
irb(main):002:0> post.permalink
=> "refinements-are-pretty-awesome"

To prove that String#permalinkify only exists within the scope of the Post class, let’s try using that method elsewhere and watch the code blow up:

irb(main):023:0> "Refinements are not globally scoped".permalinkify
NoMethodError: undefined method `permalinkify' for "Refinements are not globally scoped":String
        from (irb):23
        from /usr/local/var/rbenv/versions/2.1.0/bin/irb:11:in `<main>'

4. Required Keyword Arguments

In Ruby 2.0, keyword arguments were introduced:

def permalinkfiy(str, delimiter: "-")
  str.downcase.split.join(delimiter)
end

Unfortunately, there wasn’t a way to mark str as being required. That’s set to change in Ruby 2.1. In order to mark an argument as required, simply leave out the default value like so:

def permalinkify(str:, delimiter: "-")
  str.downcase.split.join(delimiter)
end

If we fill in all the required arguments, everything works as expected. However if we leave something out, an ArgumentError gets thrown:

irb(main):001:0> permalinkify(str: "Required keyword arguments have arrived!", delimiter: "-lol-")
=> "required-lol-keyword-lol-arguments-lol-have-lol-arrived!"
irb(main):002:0> permalinkify(delimiter: "-lol-")
ArgumentError: missing keyword: str
        from (irb):49
        from /usr/local/var/rbenv/versions/2.1.0/bin/irb:11:in `<main>'

5. Restricted Generational Garbage Collector (RGenGC)

Ruby 2.1 has a new garbage collector that uses a generational garbage collection algorithm.

The key idea and observation is that objects that are most recently created often die young. Therefore, we can split objects into young and old based on whether they survive a garbage collection run. This way, the garbage collector can concentrate on freeing up memory on the young generation.

In the event we run out of memory even after garbage collecting the young generation (minor GC), the garbage collector will then proceed on to the old generation (major GC).

Prior to Ruby 2.1, Ruby’s garbage collector was running a conservative stop-the-world mark and sweep algorithm. In Ruby 2.1, we are still using the mark and sweep algorithm to garbage collect the young/old generations. However, because we have lesser objects to mark the marking time decreases, which leads to improved collector performance.

There are caveats, however. In order to preserve compatibility with C extensions, the Ruby core team could not implement a “full” generational garbage collection algorithm. In particular, they could not implement the moving garbage collection algorithm – hence the “restricted”.

That said, it is very encouraging to see the Ruby core team taking garbage collection performance very seriously. For more details, do check out this excellent presentation by Koichi Sasada.

6. Exception#cause

Charles Nutter, who implemented this feature, explains it best:

Often when a lower-level API raises an exception, we would like to re-raise a different exception specific to our API or library. Currently in Ruby, only our new exception is ever seen by users; the original exception is lost forever, unless the user decides to dig around our library and log it.

We need a way to have an exception carry a “cause” along with it.

Here is an example of how Exception#cause works:

class ExceptionalClass
  def exceptional_method
    cause = nil
    begin
      raise "Boom!"" # RuntimeError raised
    rescue => e
      raise StandardError, "Ka-pow!"
    end
  end
end

begin
  ExceptionalClass.new.exceptional_method
rescue Exception => e
  puts "Caught Exception: #{e.message} [#{e.class}]"
  puts "Caused by       : #{e.cause.message} [#{e.cause.class}]"
end

This is what you will get:

Caught Exception: Ka-pow! [StandardError]
Caused by       : Boom! [RuntimeError]

7. Object Allocation Tracing

If you have a bloated Ruby application, it is usually a non-trivial task to pinpoint the exact source of the problem. MRI Ruby still doesn’t have profiling tools that can rival, for example, the JRuby profiler.

Fortunately, work has begun to provide object allocation tracing to MRI Ruby.

Here’s an example:

require 'objspace'

class Post
  def initialize(title)
    @title = title
  end

  def tags
    %w(ruby programming code).map do |tag|
      tag.upcase
    end
  end
end

ObjectSpace.trace_object_allocations_start
a = Post.new("title")
b = a.tags
ObjectSpace.trace_object_allocations_stop

puts ObjectSpace.allocation_sourcefile(a) # post.rb
puts ObjectSpace.allocation_sourceline(a) # 16
puts ObjectSpace.allocation_class_path(a) # Class
puts ObjectSpace.allocation_method_id(a)  # new

puts ObjectSpace.allocation_sourcefile(b) # post.rb
puts ObjectSpace.allocation_sourceline(b) # 9
puts ObjectSpace.allocation_class_path(b) # Array
puts ObjectSpace.allocation_method_id(b)  # map

Although knowing that we can obtain this information is great, it is not immediately obvious how this could be useful to you, the developer.

Enter the allocation_stats gem written by Sam Rawlins.

Let’s install it:

% gem install allocation_stats
Fetching: allocation_stats-0.1.2.gem (100%)
Successfully installed allocation_stats-0.1.2
Parsing documentation for allocation_stats-0.1.2
Installing ri documentation for allocation_stats-0.1.2
Done installing documentation for allocation_stats after 0 seconds
1 gem installed

Here’s the same example as before, except that we are using allocation_stats this time:

require 'allocation_stats'

class Post
  def initialize(title)
    @title = title
  end

  def tags
    %w(ruby programming code).map do |tag|
      tag.upcase
    end
  end
end

stats = AllocationStats.trace do
  post = Post.new("title")
  post.tags
end

puts stats.allocations(alias_paths: true).to_text

Running this produces a nicely formatted table:

sourcefile  sourceline  class_path  method_id  memsize  class
----------  ----------  ----------  ---------  -------  ------
post.rb             10  String      upcase           0  String
post.rb             10  String      upcase           0  String
post.rb             10  String      upcase           0  String
post.rb              9  Array       map              0  Array
post.rb              9  Post        tags             0  Array
post.rb              9  Post        tags             0  String
post.rb              9  Post        tags             0  String
post.rb              9  Post        tags             0  String
post.rb             17  Class       new              0  Post
post.rb             17                               0  String

Sam gave a wonderful presentation that looks into more details of the allocation_stats gem.

Happy Holidays!

Ruby 2.1 is scheduled to be released on Christmas day. If everything goes well, it would make for a wonderful present for all Rubyists. I am especially excited to see improvements in Ruby’s garbage collector, and also better profiling capabilities baked into the language that allow for the building of better profiling tools.

Happy coding and happy holidays!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • boriscy

    Wow refinements is by far my favorite new feature. !!!, nice article

  • Pavel Pravosud

    1) Published January 2, 2014
    2) Ruby 2.1.0-preview2, which is the latest release at the time of this writing

    These two sentences do not go well together. I guess you can safely replace all occurrences of preview2 with p0 and it’d still be right.

    • Guest

      Fixed! Thanks Pavel.