[前][次][番号順一覧][スレッド一覧]

ruby-changes:7059

From: matz <ko1@a...>
Date: Wed, 13 Aug 2008 17:44:33 +0900 (JST)
Subject: [ruby-changes:7059] Ruby:r18577 (trunk): * hash.c (rb_hash_set_default_proc): add new method. a patch from

matz	2008-08-13 17:44:17 +0900 (Wed, 13 Aug 2008)

  New Revision: 18577

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=18577

  Log:
    * hash.c (rb_hash_set_default_proc): add new method.  a patch from
      Giuseppe Bilotta.  #419

  Modified files:
    trunk/ChangeLog
    trunk/hash.c

Index: ChangeLog
===================================================================
--- ChangeLog	(revision 18576)
+++ ChangeLog	(revision 18577)
@@ -3,6 +3,11 @@
 	* transcode.c (transcode_restartable0): several local variables
 	  removed.
 
+Wed Aug 13 17:35:23 2008  Yukihiro Matsumoto  <matz@r...>
+
+	* hash.c (rb_hash_set_default_proc): add new method.  a patch from
+	  Giuseppe Bilotta.  #419
+
 Wed Aug 13 17:31:12 2008  Yukihiro Matsumoto  <matz@r...>
 
 	* vm_insnhelper.c (caller_setup_args): should ensure if the value
Index: hash.c
===================================================================
--- hash.c	(revision 18576)
+++ hash.c	(revision 18577)
@@ -11,6 +11,7 @@
 
 **********************************************************************/
 
+#include "eval_intern.h"
 #include "ruby/ruby.h"
 #include "ruby/st.h"
 #include "ruby/util.h"
@@ -623,6 +624,37 @@
     return Qnil;
 }
 
+/*
+ *  call-seq:
+ *     hsh.default_proc = proc_obj     => proc_obj
+ *
+ *  Sets the default proc to be executed on each key lookup.
+ *
+ *     h.default_proc = proc do |hash, key|
+ *       hash[key] = key + key
+ *     end
+ *     h[2]       #=> 4
+ *     h["cat"]   #=> "catcat"
+ */
+
+static VALUE
+rb_hash_set_default_proc(VALUE hash, VALUE proc)
+{
+    VALUE b;
+
+    rb_hash_modify(hash);
+    b = rb_check_convert_type(proc, T_DATA, "Proc", "to_proc");
+    if (NIL_P(b) || !rb_obj_is_proc(b)) {
+	rb_raise(rb_eTypeError,
+		 "wrong default_proc type %s (expected Proc)",
+		 rb_obj_classname(proc));
+    }
+    proc = b;
+    RHASH(hash)->ifnone = proc;
+    FL_SET(hash, HASH_PROC_DEFAULT);
+    return proc;
+}
+
 static int
 key_i(VALUE key, VALUE value, VALUE *args)
 {
@@ -2596,6 +2628,7 @@
     rb_define_method(rb_cHash,"default", rb_hash_default, -1);
     rb_define_method(rb_cHash,"default=", rb_hash_set_default, 1);
     rb_define_method(rb_cHash,"default_proc", rb_hash_default_proc, 0);
+    rb_define_method(rb_cHash,"default_proc=", rb_hash_set_default_proc, 1);
     rb_define_method(rb_cHash,"key", rb_hash_key, 1);
     rb_define_method(rb_cHash,"index", rb_hash_index, 1);
     rb_define_method(rb_cHash,"size", rb_hash_size, 0);

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]