I’ve seen how Ruby uses an initialize() method as a constructor.
Can this method be overloaded? After playing with IRB I’m assuming it can’t?
Thanks very much again; Ruby and this list are great.
For better or worse, no method can be overloaded, unless you ask Guy for his
modified Ruby
If you need to branch on type, you can do this
def initialize(value)
case value
when String then …
when Regexp then …
else …
end
If you need variable arguments, you can do
def initialize (value, *values)
process(value)
values.each do |v|
…
end
end
Then, of course, there’s default arguments:
def initialize(size=5, shape=SQUARE, colour=nil, params={})
@colour = nil || @colour || DEFAULT_COLOUR
…
end
Finally, if your method expects a String, do the following:
def initialize(s)
process(s.to_s) # Now it can handle numbers, etc, too.
end
(This doesn’t always feel right. Use your judgement in each case.)
So there are ways to handle the need for varying parameter lists (a la
overloaded methods). None of them are a perfect fit from the point of view of
some other languages, but it’s pretty rare that the above approaches can’t
provide a decent solution.
Note to FAQ maintainer: this proposed FAQ entry is in response to
ruby-talk:56440. Please examine any other responses if/when entering this.
Gavin
···
From: christopher.j.meisenzahl@citicorp.com