hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Method Check: Param Hacks #

by why in inspect

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
said on 14 Feb 2005 at 17:16

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!

said on 14 Feb 2005 at 19:41

That is transglorious. An excellent find!

said on 14 Feb 2005 at 20:03

I feel the power.

said on 14 Feb 2005 at 23:01

Brilliant, especially the referring to earlier parameters part.

said on 15 Feb 2005 at 08:26

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 .

said on 15 Feb 2005 at 10:16
It would be nice if we could use instance variables as an lvalue in the parameter list to save a step. In other words:
class Foo
   attr_accessor :bar, :baz
   def initialize(@bar=1,@baz=2); end
end
instead of the long way:
class Foo
   attr_accessor :bar, :baz
   def initialize(bar=1,baz=2)
       @bar, @baz = bar, baz
   end
end
I thought that Paul Brannan’s “RubyTreasures” had some method for doing this, but I don’t see it now (and I can’t get it to compile anyway). Maybe it’s in one of flgr’s evil bag o’ tricks.
said on 15 Feb 2005 at 10:23

This is plain cool. I like that you mention tricks like that. Another good find was the trick with ‘defined?’ keyword.

said on 15 Feb 2005 at 12:01

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.