문제

So I have some functions in Ruby 1.9 where it would be really, really nice to do the functional equivalent of this:

def foo(**kwargs):
    ...do stuff...

def bar(**kwargs):
    foo(x = 2, y = 3, **kwargs)

So Ruby has opts, but if I do this:

def f(opts)
    print opts.keys
end

def g(opts)
    f(opts, :bar=>3)
end

g(:foo => 1)

I get:

script:1:in f': wrong number of arguments (2 for 1) (ArgumentError) from script:6:in g' from script:9:in <main>'

Is there a way to pass opts through from g into f?

도움이 되었습니까?

해결책

Your

def g(opts)
    f(opts, :bar=>3)
end

passes two arguments to f. To let is pass one, do this:

def g(opts)
    f(opts.merge(:bar=>3))
end

다른 팁

Like below?

def f(opts)
    print opts.keys
end

def g(opts)
    opts[:bar] = 3
    f(opts)
end

g(:foo => 1)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top