Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
SmartInit: Smarter var-args constructors in Ruby

SmartInit: Smarter var-args constructors in Ruby

I was working on a small Ruby program today and I repeatedy needed to write classes that can accept a variable number of arguments in their constructors.

This is the initial solution I came up with:

class MyClass  
    def initialize(*args)       
        init_methd_name = "_init_#{args.size}"      
        send(init_methd_name, *args)        
    end

protected

    def _init_0
        puts "_init_0"
    end

    def _init_1(arg1)
        puts "_init_1: " + arg1
    end

    def _init_2(arg1, arg2)
        puts "_init_2: " + arg1 + " " + arg2
    end
end

MyClass.new
# => "_init_0"

MyClass.new("Arg 1")
# => "_init_1: Arg1"

MyClass.new("Arg 1", "Arg 2")
# => "_init_2: Arg 1, Arg 2"

In order to avoid defining #initialize like this over and over again, the #initialize method can be moved into its own module:

module SmartInit
    def initialize(*args)       
        init_methd_name = "_init_#{args.size}"      
        send(init_methd_name, *args)        
    end
end

SmartInit can then be used similar to this:

class MyClass
    include SmartInit

protected

    def _init_0
        puts "_init_0"
    end

    def _init_1(arg1)
        puts "_init_1: " + arg1
    end

    def _init_2(arg1, arg2)
        puts "_init_2: " + arg1 + " " + arg2
    end
end
@Michael-Gannon

Here's a variation on the same idea that would require less typing:

https://gist.github.com/Michael-Gannon/4734608

(should probably have linked these way back in the day)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.