2

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.

7
  • Where is ls defined in Ruby? Commented Feb 10, 2017 at 15:57
  • It isn't. That's the point. I made my own function and I'll call it using "ls" Commented Feb 10, 2017 at 15:59
  • So if the command is "pwd", then Ruby should call Dir.pwd and if the command is "ls", then Ruby should call your own ls method. Is that correct? Commented Feb 10, 2017 at 16:03
  • Yes, that is correct. Commented Feb 10, 2017 at 16:04
  • Oh, you've edited your question. Is there a class that has a method with the same name for each command? Commented Feb 10, 2017 at 16:08

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

I'm already on the third approach. However, command is a string. to_sym will only make, for example :"pwd"
Yes, what is wrong with that? You pass a symbol to send, :"pwd" is a symbol.
But that wont call pwd, will it?
yes, send(:pwd) will call the pwd method you've defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.