ruby

Ruby: How to list methods declared in the main scope


In vanilla ruby, if I create methods in the default main scope:

def asdf
    puts "asdf"
end

def qwer
    puts "qwer"
end

How do I list these functions?

I have tried the following with no luck:

methods.grep(/asdf|qwer/)
self.methods.grep(/asdf|qwer/)
Object.methods.grep(/asdf|qwer/)
Object.instance_methods.grep(/asdf|qwer/)

I'm running ruby on Windows 10, installed via https://scoop.sh/:

> ruby --version
ruby 3.3.1 (2024-04-23 revision c56cd86388) [x64-mingw-ucrt]

Solution

  • Methods created in main scope (these are methods not functions) are private visibitility.

    This means that you are looking for them in the wrong place.

    Instead, do private_methods while you are in main scope as this will list the private methods that are defined for Object, which is where main scope is.

    Example:

    def asdf
        puts "asdf"
    end
    
    def qwer
        puts "qwer"
    end
    
    puts private_methods.grep(/asdf/)