diff options
author | knu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2010-11-17 09:29:49 +0000 |
---|---|---|
committer | knu <knu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2010-11-17 09:29:49 +0000 |
commit | abe08c78108cd09da9ef1c26313177e088a0f562 (patch) | |
tree | 2faad5e41a1897e7a85fbe1e7c0ff9c8b4655656 | |
parent | f8ee9c7c3e025bd87d785adcc3adbf627dcaa788 (diff) |
* array.c (rb_ary_sort_by_bang): Add Array#sort_by!.
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@29815 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r-- | ChangeLog | 4 | ||||
-rw-r--r-- | NEWS | 4 | ||||
-rw-r--r-- | array.c | 36 | ||||
-rw-r--r-- | test/ruby/test_array.rb | 6 |
4 files changed, 50 insertions, 0 deletions
@@ -1,3 +1,7 @@ +Wed Nov 17 18:28:27 2010 Akinori MUSHA <[email protected]> + + * array.c (rb_ary_sort_by_bang): Add Array#sort_by!. + Mon Nov 1 00:58:00 2010 Akinori MUSHA <[email protected]> * ext/digest/digest.c (rb_digest_class_init): Define @@ -70,6 +70,10 @@ with all sufficient information, see the ChangeLog file. New method which replaces #choice. + * Array#sort_by! + + New method. + * Enumerable#each_entry New method. @@ -1845,6 +1845,41 @@ rb_ary_sort(ary) return ary; } + +static VALUE sort_by_i _((VALUE)); + +static VALUE +sort_by_i(i) + VALUE i; +{ + return rb_yield(i); +} + +/* + * call-seq: + * ary.sort_by! {| obj | block } -> ary + * ary.sort_by! -> an_enumerator + * + * Sorts +self+ in place using a set of keys generated by mapping the + * values in +self+ through the given block. + * + * If no block is given, an enumerator is returned instead. + * + */ + +static VALUE +rb_ary_sort_by_bang(ary) + VALUE ary; +{ + VALUE sorted; + + RETURN_ENUMERATOR(ary, 0, 0); + rb_ary_modify(ary); + sorted = rb_block_call(ary, rb_intern("sort_by"), 0, 0, sort_by_i, 0); + rb_ary_replace(ary, sorted); + return ary; +} + /* * call-seq: * array.collect {|item| block } -> an_array @@ -3903,6 +3938,7 @@ Init_Array() rb_define_method(rb_cArray, "reverse!", rb_ary_reverse_bang, 0); rb_define_method(rb_cArray, "sort", rb_ary_sort, 0); rb_define_method(rb_cArray, "sort!", rb_ary_sort_bang, 0); + rb_define_method(rb_cArray, "sort_by!", rb_ary_sort_by_bang, 0); rb_define_method(rb_cArray, "collect", rb_ary_collect, 0); rb_define_method(rb_cArray, "collect!", rb_ary_collect_bang, 0); rb_define_method(rb_cArray, "map", rb_ary_collect, 0); diff --git a/test/ruby/test_array.rb b/test/ruby/test_array.rb index d5f1594548..31a09ac335 100644 --- a/test/ruby/test_array.rb +++ b/test/ruby/test_array.rb @@ -1334,4 +1334,10 @@ class TestArray < Test::Unit::TestCase end ) end + + def test_sort_by! + a = [1,3,5,2,4] + a.sort_by! {|x| -x } + assert_equal([5,4,3,2,1], a) + end end |