How can I automatically forward all paramters from one method to another in Ruby?

948 views Asked by At

If I have methods:

def method_a(p1, p2)
  # do some stuff
  method_b(p1, p2)
end

def method_b(p1, p2)
  # do other stuff
end

Is there a way to call method_b and automatically pass all parameters to it? (Sort like how you can call super and it automatically forwards all params)

4

There are 4 answers

2
Малъ Скрылевъ On BEST ANSWER

I know one appriximate method:

def method_a *args
   # do some stuff
   method_b *args
end

def method_b *args
   # do other stuff
end

or expanding arguments in the second method:

def method_a *args
   # do some stuff
   method_b *args
end

def method_b p1, p2
   # do other stuff
end

Since super is key-work method, the ruby interperter can treat it as of the same argument list as in the specific method you've called. But default from to call a method without argument is the same as for super method, just method name:

method_a # calls to :method_a without arguments, not as the same argument list for the caller method.

So, it will be strong omonim for the call method syntax.

1
Matzi On

Use *args like this:

def method_a(*args)
  ...
  method_b(*args)
end

def method_b(p1, p2)
  ...
end

You can process the arguments like an array in the method_a.

0
Max On

Wow, this is hacky. But it works

def fwd_call b, meth
  send(meth, *b.eval('method(__method__).parameters.map { |p| eval(p.last.to_s) }'))
end

def method1 x, y
  fwd_call(binding, :method2)
end

def method2 x, y
  x+y
end

puts method1(3, 4)
# 7
2
sawa On

Considering arbitrary number of arguments and a possibility of a block, the most general format is:

def method_a(*args, &pr)
  # do some stuff
  method_b(*args, &pr)
end

Then, in the definition of method_b, you can set a specific number of arguments and whether or not it takes a block.