Reputation: 8424
Suppose I have
class SomeClass
def some_public_method
method_1
method_2
end
where method_1
and method_2
won't be used by anything except some_public_method
.
They can be defined inside that method:
class SomeClass
def some_public_method
def method_1
p 'hi'
end
def method_2
p 'there'
end
method_1
method_2
end
end
or defined separately as private ones in the class. I was wondering which approach will be easier to maintain in the future and why (should these methods "belong" to some_public_method and not created unless some_public_method is created or they should belong to the class). I think this question isn't opinion-based because of the why part. Please provide examples of how some other code might conflict with either of these two approaches to prove your point on why either approach is better for more maintainable code.
Upvotes: 1
Views: 63
Reputation: 44685
There are no such a thing as nested methods in ruby, but you can write methods which define new methods. By doing this:
class SomeClass
def some_public_method
def method_1
p 'hi'
end
def method_2
p 'there'
end
method_1
method_2
end
end
Methods method_1
and method2
are not defined just after class is declared, because their definitions has not been executed. As soon as you execute some_public_method
, those definitions are executed and both methods are added to the class. Whether they are public or private depends on whether methods private
, protected
or public
(Yep, those are methods) has been executed against the class or not. If none of those methods has been executed, they are public.
s = SomeClass.new
t = SomeClass.new
s.method_1 #=> undefined method error
t.some_public_method
s.method_1 #=> hi
If you run some_public_method
again, those methods will be redefined which may result in a warning.
In short, do not nest method definitions, unless you are going for some nice metaprograming feature. Even then it is probably better to use define_method
method.
Upvotes: 2