Is there a way to do python's kwargs passthrough in ruby 1.9.3?

2k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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
0
On

Like below?

def f(opts)
    print opts.keys
end

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

g(:foo => 1)