问题描述:

How to make cleaner such code:

def some_public_method(arg)

var1 = private_method(arg)

var2 = private_method1(var1) if var1

var3 = private_method2(var2) if var2

var4 = private_method3(var3) if var3

private_method4(var4) if var4

end

UPDATE: sorry, forgot to change method names

网友答案:

This is one way you could do it.

Code

def some_public_method(private_methods, arg)
  private_methods.reduce(arg) { |x,m| x && send(m, x) }
end

private

def pm1(arg); arg+1; end
def pm2(arg); arg+2; end
def pm3(arg); arg+3; end

Examples

private_methods = [:pm1, :pm2, :pm3]

some_public_method(private_methods, 0) #=> 6

def pm2(arg); nil; end
some_public_method(private_methods, 0) #=> nil
相关阅读:
Top