rubyhashsplat

Hash Destructuring


You can destructure an array by using the splat operator.

def foo(arg1, arg2, arg3)
  #...Do Stuff...
end
array = ['arg2', 'arg3']
foo('arg1', *array)

But is there a way to destruct a hash for option type goodness?

def foo(arg1, opts)
  #...Do Stuff with an opts hash...
end
opts = {hash2: 'bar', hash3: 'baz'}
foo('arg1', hash1: 'foo', *opts)

If not native ruby, has Rails added something like this?

Currently I'm doing roughly this with

foo('arg1', opts.merge(hash1: 'foo'))

Solution

  • It's 2018 and this deserves an update. Ruby 2.0 introduced keyword arguments and with that also the hash splat operator **. Now you can simply do the following:

    def foo(arg1, opts)
      [arg1, opts]
    end
    
    opts = {hash2: 'bar', hash3: 'baz'}
    foo('arg1', hash1: 'foo', **opts)
    #=> ["arg1", {:hash1=>"foo", :hash2=>"bar", :hash3=>"baz"}]