This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Parameters in Ruby
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
One of the minor nits with Object#initialize in Ruby is that you can't automatically generate instance variables based on the parameters. You have to do it manually, like so:
class Foo
def initialize(bar=1,baz=2)
@bar, @bar = bar, baz
end
end
I was reading Why's Journal on parameter hacks. This reminded me that it would be nice if you could do something like this:
class Foo
def initialize(@bar=1,@baz=2)
end
end
This would save you a step. It's a nice idea, and one that David Black brought up back in 2001. There were some interesting solutions in general in that thread but, ultimately, Matz rejected the idea.
This had me thinking, however. That approach is still a little ugly syntactically. Why not just autogenerate the instance variables based on the parameter list? That way you could do:
class Foo
def initialize(bar=1,baz=2)
end
end
And, secretly behind the scenes, @bar and @baz would be set to 1 and 2 respectively. There are still no accessors, unless you add them yourself, so their data is still invisible to the outside world. Is there a drawback to this that I'm missing?
I'm sure there's a way to do this by redefining Object#initialize or Class#new or something, but I can't get it to work.