Charles Oliver Nutter
7/1/2008 1:12:00 PM
John Maclean wrote:
> =begin
> Hey chaps,
>
> Is it bad practice to have nested methods? I'm sure that it would
> result in messey/cluttered code. Does any one actually code like that
> at all? Not really -essential- as everything is working, (even better
> than), as expected without nested methods. Just would be nice to know
> what the gurus andmy peers think on this one.
>
> - jjm
> =end
>
> class Foo
> def initialize(this, that, the_other)
> @this = this
> ..
> end
>
> def method_1?
> # here I check for some criteria
> if %x[some_command] == "some criteria"
> @this = true
> end
>
> # every other method from here on depends on @this == true. Would be nice to be able to skip the remained of the code if @this != true
>
> def method_2
> # do all of this stuff if @this = true
> end
If you intend to skip defining those other methods, you need a state
variable (constant, class var, whatever) that has a lifespan longer than
that of the instances of your class. @this is going to be nil until set
by method_1?, which can only be called against an instance of Foo, which
can only happen after Foo has already been defined along with the
methods in Foo. But you can put such logic in the Foo class object to
achieve the effect you're looking for:
class Foo
class << self
def method_1?
# here I check for some criteria
if %x[some_command] == "some criteria"
true
else
false
end
end
end
if method_1?
def method_2
# etc
end
end
end
method_2 will only be defined if your criteria is met.
- Charlie