Double-splat operator - destructive vs nondestructive

Hi all,

I’m new to the forum and the double-splat is difficult to search for, so
forgive me if this question has been addressed elsewhere.

I noticed what I find to be a very surprising behavior with the **
(double-splat) operator in Ruby 2.1.1.

When key-value pairs are used before a **hash, the hash remains
unmodified; however, when key-value pairs are used only after the
**hash, the
hash is permanently modified.

Here is the smallest example of this (UPDATE: I’m replacing an earlier
version):

h = { b: 2 }

{ a: 1, **h } # => { a: 1, b: 2 }
h # => { b: 2 }

{ a: 1, **h, c: 3 } # => { a: 1, b: 2, c: 3 }
h # => { b: 2 }

{ **h, c: 3 } # => { b: 2, c: 3 }
h # => { b: 2, c: 3 }

For comparison, consider the behavior of the single-* operator on
arrays:

a = [2]

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

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

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

Is this behavior intentional? If so, where can I find the documentation
describing how the ** operator works?

I’ve fielded this question with the stackoverflow crowd as well:
http://stackoverflow.com/questions/23282342/ruby-double-splat-operator-destructive-vs-nondestructive

Thanks,
-Jesse Sielaff

I’d vote for a bug as I don’t see any supportive or even imaginable
reason why double-splat operator may alter an object applied at, for its
expansion.

Only on the left side of an assignment expression or at proc/method
arguments definiton it may be altered.

As you’ve already pointed out, it would be also inconsistent to single
splat operator.

Would be surprised if anybody would bring some meaningful explanation
why it is not a bug but correct behavior.

Thanks for your response, David. I’ve submitted it to ruby-trunk as a
bug:

https://bugs.ruby-lang.org/issues/9776

Jesse Sielaff wrote in post #1144000:

the double-splat is difficult to search for

This might help you for future code searching:
http://www.symbolhound.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs