Skip to content

Instantly share code, notes, and snippets.

@behrangsa
Last active December 12, 2015 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save behrangsa/4701009 to your computer and use it in GitHub Desktop.
Save behrangsa/4701009 to your computer and use it in GitHub Desktop.
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
Copy link

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