Pergunta

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?

Foi útil?

Solução

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

Outras dicas

Like below?

def f(opts)
    print opts.keys
end

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

g(:foo => 1)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top