Favorite Changes in Ruby 2.1

With any Ruby upgrade, I like to take a moment and consider how the improvements might change my coding style. Here’re my favorites from Ruby 2.1.

def returns method name

This may seem minor at first glance, but I think it’s a brilliant way to enable familiar syntax without introducing new language constructs or keywords.

Before

def foo
  # ...
end
protected :foo

After

protected def foo
  # ...
end

Bonus: other libraries can also take advantage!

memoize def foo
  # ...
end

Required keyword arguments

A nice quality of life improvement for keyword arguments. I’m already happy to have fewer options = {} parameters in my method definitions, and this adds some extra utility with an unsurprising syntax.

Before

Find some way to raise an exception yourself.

def foo(bar: nil, baz: nil, qux: nil)
  raise ArgumentError unless bar && baz && qux
  #...
end

After

Write less, not more.

def foo(bar:, baz:, qux:)
  #...
end

Array#to_h alternative to Hash[arr]

I’ve always found the Hash.[] method awkward. Typing it feels like an interruption, requiring a jump back to the beginning of the line. And there’s the extra pair of brackets. Now we can use Array#to_h instead!

Before

Hash[hsh.map{|k, v| [k, v.upcase] }]

After

hsh.map{|k, v| [k, v.upcase] }.to_h

Honorable Mention: Generational GC

This may not affect how I write code, but it’s worth mentioning nonetheless! Any upgrade that shaves time off garbage collection is welcome. Check out RGenGC for a concise overview of Ruby GC changes.

Is Ruby Fast Yet? shows only a marginal effect on bare Rails actions and startups. I think the effect should be more substantial on intense actions with more ActiveRecord objects and template generation.