A Look at Ruby 2.1

Share this article

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!

Benjamin Tan Wei HaoBenjamin Tan Wei Hao
View Author

Benjamin is a Software Engineer at EasyMile, Singapore where he spends most of his time wrangling data pipelines and automating all the things. He is the author of The Little Elixir and OTP Guidebook and Mastering Ruby Closures Book. Deathly afraid of being irrelevant, is always trying to catch up on his ever-growing reading list. He blogs, codes and tweets.

Share this article
Read Next
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Quick Tip: Understanding React Tooltip
Quick Tip: Understanding React Tooltip
Dianne Pena
Get the freshest news and resources for developers, designers and digital creators in your inbox each week