Top Level Functions In Ruby
While working on Matasano crypto challenges, I reached a stage where I could reuse the functions I had written in previous exercises.
So let’s suppose I had a function
foo in 1.rb
I need the function
foo in my second script named
main if __FILE__ == $0
Running the script 2.rb on terminal gives me the error
$ ruby 2.rb
2.rb:5:in `main': undefined method `foo’ for 1:Fixnum (NoMethodError)
from 2.rb:8:in `<main>'
This lead me to learning ruby access controls.
So the top level methods are
private by default and belong to
self which is a direct instance of
Object itself. This means we can never call these methods with an
In this case,
1 is an
explicit receiver which has been imported in
The not-so-good solution I have found for the time being is to mark the required top level function public explicitly.
The possible solution might be to use modules, but I am yet to reach that state.