Robert Klemme
11/4/2003 10:48:00 AM
"Eric-Roger Bruecklmeier" <news01@eric-bruecklmeier.de> schrieb im
Newsbeitrag news:3FA765CB.2010805@eric-bruecklmeier.de...
> Hi rubyists,
>
> i try so solve the following problem:
>
>
> class Foo
>
> def initialize(par)
>
> if par 'not good'
> return nil <= ???
> else
>
> do something usefull
>
> end
>
> end
>
>
> The goal is to create an instance of NilClass instead of Foo if par has
> certain attributes:
>
> test = Foo.new(good)
> p test.class -> Foo
>
> test = Foo.new(bad)
> p test.class -> NilClass
>
> Any suggestions how this can be done?
>
> Thanx!
Exceptions are the appropriate means:
class Foo
def initialize(par)
raise ArgumentError, "Not ok: #{par}" unless /ok/ =~ par
# do something useful
end
end
begin
x = Foo.new "par"
# work with x
rescue ArgumentError => e
# handle error
end
Of course you can encapsulate it in a method and return nil as error
handling. But then you will have to check for nil in other places. It
depends on the application whether that is ok or not.
Regards
robert