Over a million developers have joined DZone.

Lazy Programmer's Initialize Method

·
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
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}