From 6b18a8c2e9540f67de5887f899d73e100c3ce13f Mon Sep 17 00:00:00 2001 From: marcandre Date: Mon, 9 Apr 2012 04:07:53 +0000 Subject: * hash.c (rb_hash_set_default_proc): Accept nil, patch by Run Paint [Feature #4234] * test/ruby/test_hash.rb: test for above. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@35268 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 7 +++++++ NEWS | 4 ++++ hash.c | 9 +++++++-- test/ruby/test_hash.rb | 4 ++++ 4 files changed, 22 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index 9ec376d4f8..d8fc17a966 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +Mon Apr 9 13:06:58 2012 Marc-Andre Lafortune + + * hash.c (rb_hash_set_default_proc): Accept nil, patch by Run Paint + [Feature #4234] + + * test/ruby/test_hash.rb: test for above. + Mon Apr 9 08:01:15 2012 Tadayoshi Funaba * ext/date/date_strftime.c: gets the value with range() consistetly. diff --git a/NEWS b/NEWS index 2c9b08b568..e390b9f09a 100644 --- a/NEWS +++ b/NEWS @@ -21,6 +21,10 @@ with all sufficient information, see the ChangeLog file. * added method: * added Enumerable#lazy method for lazy enumeration. + * Hash + * extended method: + * Hash#default_proc= can be passed nil to clear the default proc. + * Kernel * added method: * added Kernel#Hash conversion method like Array() or Float(). diff --git a/hash.c b/hash.c index 4764bdd6b2..9d14d3f73f 100644 --- a/hash.c +++ b/hash.c @@ -689,9 +689,9 @@ rb_hash_default_proc(VALUE hash) /* * call-seq: - * hsh.default_proc = proc_obj -> proc_obj + * hsh.default_proc = proc_obj or nil * - * Sets the default proc to be executed on each key lookup. + * Sets the default proc to be executed on each failed key lookup. * * h.default_proc = proc do |hash, key| * hash[key] = key + key @@ -706,6 +706,11 @@ rb_hash_set_default_proc(VALUE hash, VALUE proc) VALUE b; rb_hash_modify_check(hash); + if (NIL_P(proc)) { + FL_UNSET(hash, HASH_PROC_DEFAULT); + RHASH_IFNONE(hash) = proc; + return proc; + } b = rb_check_convert_type(proc, T_DATA, "Proc", "to_proc"); if (NIL_P(b) || !rb_obj_is_proc(b)) { rb_raise(rb_eTypeError, diff --git a/test/ruby/test_hash.rb b/test/ruby/test_hash.rb index bcfe13cbb3..e3c92125c5 100644 --- a/test/ruby/test_hash.rb +++ b/test/ruby/test_hash.rb @@ -718,6 +718,10 @@ class TestHash < Test::Unit::TestCase def test_default_proc h = Hash.new {|hh, k| hh + k + "baz" } assert_equal("foobarbaz", h.default_proc.call("foo", "bar")) + assert_nil(h.default_proc = nil) + assert_nil(h.default_proc) + h.default_proc = ->(h, k){ true } + assert(h[:nope]) h = {} assert_nil(h.default_proc) end -- cgit v1.2.3