Ruby Method Parameter Default Values – A Shortcut

Today was one of those moments where I thought to myself: “wouldn’t it be cool if I could”… and it turned out I could. In Ruby, you can give your method parameters default values:

def my_method(a = 5)
	puts a

my_method # outputs: 5

So far, so ordinary. But you can also do something a bit more interesting – populate your parameter defaults from instance variables:

class MyClass
	def initialize
		@default_a = 5

	def my_method(a = @default_a)
		puts a
end # outputs: 5

There’s probably some Ruby gurus looking at this and thinking *OH MY GOD WHAT ARE YOU DOING* but in my case, it saved me having to create a method which “seeded” a second method with some default values; a few lines of code successfully saved.

Related Articles:

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    This entry was posted in ruby. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

    Comments are closed.