S
S
Sergey Antonov2016-07-05 14:27:19
Iron
Sergey Antonov, 2016-07-05 14:27:19

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

4 answer(s)
S
Sergey Antonov, 2016-07-05
@ArteNonMarte

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);

In summary, the question is: how to call a method if its name came in a variable, or does the method name need to be constructed?
upd
Solution found (at least one), using send:
def router(act, data)
  m = 'prefix_' + act
  send(m, data)	
end

M
mukizu, 2016-07-05
@mukizu

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)

M
Max, 2016-07-05
@maxprof

def hello
    puts "Hello"
end

hello

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question