In reply to a post today on ruby-talk, I came up with this monkey-patch that lets you write long initialize methods in one line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
require 'generator'

module InitializesWith
  def initializes_with(*params)
    define_method :initialize do |*args|
      iterator = SyncEnumerator.new(params, args)
      iterator.each do |param, arg|
        instance_variable_set "@#{param}", arg
      end
    end
  end
end

class Class
  include InitializesWith
end

class C
  attr_reader :x, :y, :z
  initializes_with :x, :y, :z
end

obj = C.new(1,2,3)

obj.x # => 1
obj.y # => 2
obj.z # => 3

There may well be a better way already out there, but it only took me a few minutes to type out.

Leave a Reply