From ad78cf4ea8613c7e1790c5e3a2718a35fe32115f Mon Sep 17 00:00:00 2001 From: knu Date: Fri, 19 Jul 2013 02:22:11 +0000 Subject: [PATCH] Define Set#to_set so that aSet.to_set returns self. * lib/set.rb (Set#to_set): Define Set#to_set so that aSet.to_set returns self. [Fixes GH-359] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@42051 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ NEWS | 4 ++++ lib/set.rb | 10 ++++++++++ test/test_set.rb | 3 +++ 4 files changed, 22 insertions(+) diff --git a/ChangeLog b/ChangeLog index ec3c88fed0..7f95617f07 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Fri Jul 19 11:16:54 2013 Akinori MUSHA + + * lib/set.rb (Set#to_set): Define Set#to_set so that aSet.to_set + returns self. [Fixes GH-359] + Fri Jul 19 11:10:23 2013 Zachary Scott * lib/rake/*: [DOC] Capitalize "Ruby" in documentation diff --git a/NEWS b/NEWS index 4594fc76af..f5fe38838d 100644 --- a/NEWS +++ b/NEWS @@ -137,6 +137,10 @@ with all sufficient information, see the ChangeLog file. === Stdlib compatibility issues (excluding feature bug fixes) +* Set + * incompatible changes: + * Set#to_set now returns self instead of generating a copy. + * URI * incompatible changes: * URI.decode_www_form follows current WHATWG URL Standard. diff --git a/lib/set.rb b/lib/set.rb index a9aa7e7936..47fcc3efc7 100644 --- a/lib/set.rb +++ b/lib/set.rb @@ -148,6 +148,16 @@ class Set @hash.keys end + # Returns self if no arguments are given. Otherwise, converts the + # set to another with klass.new(self, *args, &block). + # + # In subclasses, returns klass.new(self, *args, &block) unless + # overridden. + def to_set(klass = Set, *args, &block) + return self if instance_of?(Set) && klass == Set && block.nil? && args.empty? + klass.new(self, *args, &block) + end + def flatten_merge(set, seen = Set.new) # :nodoc: set.each { |e| if e.is_a?(Set) diff --git a/test/test_set.rb b/test/test_set.rb index 26950c3e30..cbf4eb0234 100644 --- a/test/test_set.rb +++ b/test/test_set.rb @@ -625,6 +625,9 @@ class TC_Enumerable < Test::Unit::TestCase assert_instance_of(Set, set) assert_equal([-10,-8,-6,-4,-2], set.sort) + assert_same set, set.to_set + assert_not_same set, set.to_set { |o| o } + set = ary.to_set(SortedSet) assert_instance_of(SortedSet, set) assert_equal([1,2,3,4,5], set.to_a)