Of Mice and Men


Array#to_proc - Nested properties for to_proc hack.

Posted in Ruby by Anders Engström on the April 18th, 2007

Ruby is really elegant when it come to extending core libraries with custom behavior.

I needed a way to apply the standard to_proc hack to nested method calls. Normally the to_proc implementation in Symbol allows you to replace

['abc', 'defg'].map{|x| x.size} #=> [3, 4]

with

['abc, 'defg'].map(&:size) #=> [3, 4]

But this only applies to “first level” methods on the target reference. The following extension of the Array class allows specifying a ‘call chain’ of methods:

class Array
  def to_proc            
    proc{|target|        
      inject(target){|memo, arg| 
        break unless memo
        memo.send(arg)            
      }
    }
  end
end

So, in order to extract the regnr of an optional default_trailer:

class Car < ActiveRecord::Base
    has_one :default_trailer, :class_name => 'Trailer'
end

class Trailer < ActiveRecord::Base
    belongs_to :car
end

you can do:

[car1, car2, car3].map(&[:default_trailer, :regnr]) 
    #=> ['GH3456', nil, 'FF1234']                   

Comments are closed.