Dynamically create a function named from the contents of a variable

I want to use IRB as a shell for my GNU/Linux system (portablility is desired but not a requirement at this point). How I hope to acheive this is to loop through each directory in the $PATH variable, then through each file in those directories and dynamically create a function named as the files name (automatically create a function for ‘/usr/bin/konsole’ named ‘konsole()’). I’m doing much more but this is kind of the corner stone of the whole project and I just can’t figure out how to create functions with the contents of a variable as it’s name. Is this even possible? If it is could someone give me a simple example of just the function creation?

You can do that using the metaprogramming eval method. For example:

x = 'test'
eval("def #{x}; puts 'Hello world'; end")
test

The eval method takes a string and parses it into code; you can insert variable values into it as I have done here. The idea that doing this is evil is a bit overblown. It’s not a good idea to do it unless you have a clear idea of what you are up to, though. In this particular use case it’s the way to do the job.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs