Friday, May 13, 2016

Methods inside methods



This is not well known, but you may define methods inside methods in Ruby. The following code is perfectly valid and runs.

The output will be

Method alfa
Method beta
Method beta

As you may see, the method beta won't disappear after method alfa finished its execution. In this point, inner methods are different from inner variables. In effect,


will output

Method alfa
1
Method beta
testing001.rb:14:in `alfa': undefined local variable or method `beta_variable' for main:Object (NameError)
from testing001.rb:18:in `<main>'

because beta_variable is not defined in method alfa scope. All the other three puts are going to generate similar errors, since we are using variables out of the scopes they were created.

This is an interesting behavior!