DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Alexey has posted 28 posts at DZone. View Full User Profile

Lazy Programmer's Initialize Method

06.24.2010
| 2808 views |
  • submit to reddit
        If initialize methods like the following one annoys you
  def initialize var1, var2
    @var1 = var1
    @var2 = var2
  end

Then here is an example of how to save a few key strokes:
  describe PrivateStruct do
    it "initializes instance variables" do

      class X < PrivateStruct.new :@a, :@b, :@c
        def get_a
          @a
        end
      end

      X.new(1,2,3).get_a.should == 1
    end
  end

And here is implementation for PrivateStruct:
  class PrivateStruct
    def self.new *instance_variables
      Class.new do
        define_method :initialize do |*values|
          instance_variables.size == values.size or raise "invalid number of arguments: expected #{instance_variables.size} got #{values.size}"
          instance_variables.zip(values).each { |name, value| instance_variable_set name, value }
        end
      end
    end
  end