Programming ≈ Fun

Written by Krešimir Bojčić

Things to Look Forward to in Ruby 2.0

I am going to list a couple of great features that are marked for Ruby 2.0 milestone.

Combined map/select method

Let say you want to map over an Enumerable and only keep elements that meet a certain criteria.

You can do it in two calls like this:

[1,2,3,4].select(&:even?).map {|i| i + 1}
==> [3, 5]
[1,2,3,4].map { |i| i + 1 if i.even? }.compact
==> [3, 5]

The idea is to have one method that combines those two. The name is still not clear but filter_map seems like a possible choice.

[1,2,3,4].filter_map { |i| i + 1 if i.even? }
==> [3, 5]

Since I didn’t want to wait I’ve chosen to make a poor man’s version and while at it give it a different name.

module Enumerable
  def map_selected(&block)
    map(&block).compact!
  end
end
[1,2,3,4].map_selected { |i| i + 1 if i.even? }
==> [3, 5]

Ruby feature #5663

Keyword arguments

I’ve been missing those ever since I realized they exist in Smalltalk. Then to my dismay I figured Lisp has them, Clojure has them and even Python has them. I had to cry myself to sleep while taking comfort in a fact that Python doesn’t have blocks.

Of course the need was not that big since you can “fake” keyword arguments with Hash but it’s nice to have a proper support:

def foo_bar(name: 'foo', last_name: 'bar')
  print "#{name} #{last_name}"
end

foo_bar ==> foo bar
foo_bar last_name: 'baruco' ==> foo baruco
foo_bar last_name: 'baruco', name:'hello' ==> hello baruco

If you don’t believe me you can go ahead and install ruby-head. This cool and long awaited feature is already implemented and the last edge cases are being ironed out.

Ruby feature #5474

Ruby feature #5454 translation

Instance var assignment in the object initializer

This common case scenario will be shorten by two lines

class FooBar
  def initialize(name, last_name)
    @name = name
    @last_name = last_name
  end

  def to_s
    "#@name #@last_name"
  end
end

print FooBar.new('foobar', 'rulez')
=> foobar rulez

Like this:

class FooBar
  def initialize(@name, @last_name)
    #nice isn't it?
  end

  def to_s
    "#@name #@last_name"
  end
end

print FooBar.new('foobar', 'rulez')
=> foobar rulez

I am sure there will be situations when this behaviour will come in handy. The feature is coming from CoffeScript as far as I can tell, but Ruby 1.8.7 had a similar trick:

define_method(:intialize){|@name, @last_name|}

Ruby feature #5825

What else?

With this I conclude my list. So, what are your favourite features in Ruby 2.0?

Comments