Method Check: Param Hacks #
It’s all about finding out where Ruby’s syntax is flexible, isn’t it? So, did you know you can use instance variables or arbitrary code to set the defaults in your method parameters? All executed in the same context as your method.
class LineArtist attr_accessor :distance, :thickness def draw( dist = @distance, thick = self.thickness ); end end
And, check this out—you can refer to earlier parameters when setting defaults!
class BlogEntry attr_accessor :author, :title, :created_at, :content def initialize( blog, title, content, created_at = Time.now, author = blog.default_author ) end end
This is especially useful for methods where you’re passing in a set of paths. If some of the paths are deleted, you want to default to an earlier path (or a new path based on an earlier path.)
class Blog def setup( path, template_path = File.join( path, "skel" ) ) end end
Tom Kirchner
Yeah, this is one of my favorite tricks. You can also create new scope inside the defaults declaration, useable in later parts of the same method declaration. Long live flexibility!
Adam Keys
That is transglorious. An excellent find!
cilibrar
I feel the power.
zem
Brilliant, especially the referring to earlier parameters part.
William
Pretty nice. Didn’t realize Ruby let you do that. R actually takes that one step further and does lazy evaluation on default values, which allows you to refer to local variables and such defined later in the function. Surprisingly useful!
Of course that’s the only nice feature of that language, IMO .
Daniel Berger
Kent
This is plain cool. I like that you mention tricks like that. Another good find was the trick with ‘defined?’ keyword.
why
Tom Kirchner: hey, thanks.
Adam Keys: thanks.
cilibrar: oh.
zem: oh, thanks.
William: R, yeah.
Daniel Berger: sure would.
Kent: sure, thanks.
And you’re all invited back for seconds.
Comments are closed for this entry.