Project

General

Profile

Actions

Feature #11710

open

[PATCH] Replace Set#merge with Set#merge! and make Set#merge non-mutating.

Added by tiegz (Tieg Zaharia) about 9 years ago. Updated 8 months ago.

Status:
Assigned
Target version:
-
[ruby-core:71560]

Description

The Set#merge method currently mutates its caller. I propose changing its behavior to non-mutating, and replace its current behavior with a mutating Set#merge! method.

For example, the current behavior:

> s = Set.new [1,2,3]  # => #<Set: {1, 2, 3}>
> s.object_id          # => 70125370250380
> s.merge([4,5,6])     # => #<Set: {1, 2, 3, 4, 5, 6}>
> s                    # => #<Set: {1, 2, 3, 4, 5, 6}>
> s.object_id          # => 70125370250380

Set describes itself as a hybrid of Array and Hash, but Hash#merge does not mutate its caller, and Set is implemented on top of Hash as well. Hash has a merge! method that can mutate instead:

> h = {a: 1, b: 2}            # => {:a=>1, :b=>2}
> h.object_id                 # => 70125369896320
> h.merge({c: 3})             # => {:a=>1, :b=>2, :c=>3}
> h                           # => {:a=>1, :b=>2}
irb(main):015:0> h.object_id  # => 70125369896320

We were taken by surprise with the existing behavior of Set#merge, especially since Set follows the bang pattern of mutating/non-mutating method names (e.g. collect!, reject!, select!, flatten!)

I noticed this has been suggested before, but was hoping it might be possible as a breaking change for 2.3.0?


Files

non_mutating_set_merge_method.diff (1.47 KB) non_mutating_set_merge_method.diff tiegz (Tieg Zaharia), 11/18/2015 05:13 PM
non_mutating_set_merge_method.2.diff (1.47 KB) non_mutating_set_merge_method.2.diff tiegz (Tieg Zaharia), 11/18/2015 07:28 PM
Actions

Also available in: Atom PDF

Like0
Like0Like0