I have a method inside of a method. The interior method depends on a variable loop that is being run. Is that a bad idea?
Join Stack Overflow to learn, share knowledge, and build your career.
|
|
UPDATE: Since this answer seems to have gotten some interest lately, I wanted to point out that there is discussion on the Ruby issue tracker to remove the feature discussed here, namely to forbid having method definitions inside a method body. No, Ruby doesn't have nested methods. You can do something like this:
But that is not a nested method. I repeat: Ruby does not have nested methods. What this is, is a dynamic method definition. When you run But where is
Also, it will obviously be redefined every time you run
In short: no, Ruby does not support nested methods. Note also that in Ruby, method bodies cannot be closures, only block bodies can. This pretty much eliminates the major use case for nested methods, since even if Ruby supported nested methods, you couldn't use the outer method's variables in the nested method. UPDATE CONTINUED: at a later stage, then, this syntax might be re-used for adding nested methods to Ruby, which would behave the way I described: they would be scoped to their containing method, i.e. invisible and inaccessible outside of their containing method body. And possibly, they would have access to their containing method's lexical scope. However, if you read the discussion I linked above, you can observe that matz is heavily against nested methods (but still for removing nested method definitions). |
|||||||||||||||||||||
|
|
The Ruby way is to fake it with confusing hacks that will have some users wondering "How in the fuck does this even work?", while the less curious will simply memorize the syntax needed to use the thing. If you've ever used Rake or Rails, you've seen this kind of thing. Here is such a hack:
What that does is define a top-level method that creates a class and passes it to a block. The class uses You use it like this:
It is possible to make a similar contraption that allows for multiple inner functions to be defined without additional nesting, but that requires an even uglier hack of the sort you might find in Rake's or Rspec's implementation. Figuring out how Rspec's |
||||
|
|
|
Actually it's possible. You can use procs/lambda for this.
|
|||
|
|
|
You can do something like this
This is useful when you're doing things like writing DSLs which require sharing of scope between methods. But otherwise, you're much better off doing anything else, because as the other answers said, |
|||
|
|
|
:-D Ruby has nested methods, only they don't do what you'd expect them to
|
|||||
|
|
No, no, Ruby does have nested methods. Check this:
|
|||||
|