0

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)

Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
ardavis
  • 9,842
  • 12
  • 58
  • 112
  • 1
    Personally; yuck. I'm not comfortable with the `super` magic, either, actually. This is one of those cases where IMO being explicit should be the default choice. – Dave Newton Dec 13 '13 at 17:07

4 Answers4

1

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.

Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
  • This is definitely a plausible way to go. Both methods will always have the same parameters (in my current case). I was hoping to name them explicitly for readability as I do now, but if this is the only option, might have to go for it. – ardavis Dec 13 '13 at 16:58
  • I added a short description why call to `super` isn't the same as call to other named method. – Малъ Скрылевъ Dec 13 '13 at 17:04
1

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
0

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.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
Matzi
  • 13,770
  • 4
  • 33
  • 50
-1

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
Max
  • 21,123
  • 5
  • 49
  • 71