Search code examples
rubyparsingirb

Find declared function from user input


I have a prompt in my "app", like irb that takes an input,I want it to parse the input and execute a function that I've defined. Similarly, my app takes an input through gets, and calls the function. For example,

command = gets.gsub("\n","")

takes an input "pwd", now I want to call the function pwd, which is defined below:

def pwd
  Dir.pwd
end

Now, I could simply use if conditions to do so, but a lot of these conditions wouldn't be as elegant as Ruby's philosophy requires it to be.

The Question

I want to parse the input to call a defined function. Like, "pwd" calls pwd, "ls" calls its equivalent function that I have defined.

How do I do this? Comment if question is still not clear. Cheers.

Addressing Possible Duplicate

The question suggested specifically wants to run Shell commands. Whereas, I am using only built-in Ruby methods and classes and maybe in the future I'll even use Gems, so as to attain platform independence. My commands may look and behave like shell, but I'm not actually running shell. Therefore, my question is not a possible duplicate.

Furthermore, future readers will find it helpful for parsing input in Ruby.


Solution

  • You can write a mapping for the different inputs in the form of a case:

    case command
    when "pwd"
      Dir.pwd # or move it into another method and call it here
    when "ls"
      # etc
    end
    

    or a hash, which is slightly more concise

    actions = {
      pwd: -> { Dir.pwd },
      ls: -> { <foobar> } 
    }
    actions[command.to_sym].call
    

    You can also make method names matching the commands and use send, but don't do this if the input is coming from strangers:

    def pwd
      Dir.pwd
    end
    
    command = command.to_sym
    send(command)