Double-splat 运算符破坏性地修改哈希——这是 Ruby 错误吗? [英] Double-splat operator destructively modifies hash – is this a Ruby bug?

查看:17
本文介绍了Double-splat 运算符破坏性地修改哈希——这是 Ruby 错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到我发现使用 Ruby 2.1.1 中的 **(双斜线)运算符有一个非常令人惊讶的行为.

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

**hash 之前使用键值对时,哈希保持不变;但是,当键值对仅在 **hash 之后使用时,哈希值会被永久修改.

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

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]

数组始终保持不变.

我们认为 ** 有时具有破坏性的行为是故意的,还是看起来更像是一个错误?

Do we suppose the sometimes-destructive behavior of ** is intentional, or does it look more like a bug?

在这两种情况下,描述 ** 运算符如何工作的文档在哪里?

In either case, where is the documentation describing how the ** operator is meant to work?

我也在在 Ruby 论坛问了这个问题.

更新

该错误已在 Ruby 2.1.3+ 中修复.

The bug is fixed in Ruby 2.1.3+.

推荐答案

问题的答案似乎是:

  1. 这可能是一个错误,而不是故意的.

  1. It's probably a bug, rather than intentional.

** 运算符的行为在 核心库 rdoc.

感谢几位评论者的建议,我已将该错误发布到 Ruby 主干问题跟踪器.

Thanks to the suggestions of several commenters, I've posted the bug to the Ruby trunk issue tracker.

更新:

该错误已在 变更集 r45724 中修复.那里的评论是关键字 splat 应该是非破坏性的",这使得这是一个权威的答案.

The bug was fixed in changeset r45724. The comment there was "keyword splat should be non-destructive," which makes this an authoritative answer.

这篇关于Double-splat 运算符破坏性地修改哈希——这是 Ruby 错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆