Answer the question
In order to leave comments, you need to log in
How to call a method by name in Ruby?
In php, for example, you can do it like this:
$m = 'gohome';
$m()
Answer the question
In order to leave comments, you need to log in
An extended illustration to the question (using an example of how this can be implemented in php) and a solution in Ruby:
class help{
function router($sex, $stuff){
$method_name = 'if_'.$sex;
$method_name($stuff);
// можно предварительно проверить наличие метода
// method_exists(где_искать, имя_метода)
// или отдать на обработку ошибок в __call()
}
function if_m($stuff){ return 'Мальчики направо'; }
function if_w($stuff){ return 'Девочки налево'; }
// аналог method_missing в Ruby
function __call($name, $param = false){
return 'Идите прямо, пока не определитесь';
}
}
$sex = 'm'
$stuff = 'какая-то важная фигня';
$h = new help();
$h.router($sex, $stuff);
def router(act, data)
m = 'prefix_' + act
send(m, data)
end
Through eval / call / send - I advise you to read more about how they work and other differences before using them.
For example
def a
puts 1
end
send(:a)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question