xxjjnn
xxjjnn

Reputation: 15239

Take a hash out of its braces

Given bar = {c: 3, d: 4}, how can you use bar to let a code in this format:

foo(a: 1, b: 2, some_code_here)

express the following?

foo(a: 1, b: 2, c: 3, d: 4)

You can splat an array:

a = [1, 2, 3]
[*a, 4] # => [1, 2, 3, 4]

How do you do this with a hash? I tried this:

a = {i: 1, j: 2, k: 3}
{*a, l: 4} # => error

Upvotes: 1

Views: 40

Answers (2)

Gagan Gami
Gagan Gami

Reputation: 10251

a = {i: 1, j: 2, k: 3}
a.merge(l: 4) #=> {:i=>1, :j=>2, :k=>3, :l=>4}

Upvotes: 1

xxjjnn
xxjjnn

Reputation: 15239

Use double splat (**):

a = {i: 1, j: 2, k: 3}
{**a, l: 4} # => {i: 1, j: 2, k: 3, l: 4}

Ruby devs: why not use the unused regular splat?

Upvotes: 4

Related Questions