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 end 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 end def my_method(a = @default_a) puts a end end MyClass.new.my_method # 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.