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

ruby-changes:23290

From: marcandre <ko1@a...>
Date: Mon, 16 Apr 2012 12:16:17 +0900 (JST)
Subject: [ruby-changes:23290] marcandRe: r35341 (trunk): * struct.c: Add Struct#to_h [Feature #6276]

marcandre	2012-04-16 12:16:10 +0900 (Mon, 16 Apr 2012)

  New Revision: 35341

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

  Log:
    * struct.c: Add Struct#to_h [Feature #6276]
      [ref #4862] [rubyspec:2082ef46d46e]

  Modified files:
    trunk/NEWS
    trunk/struct.c

Index: struct.c
===================================================================
--- struct.c	(revision 35340)
+++ struct.c	(revision 35341)
@@ -586,6 +586,31 @@
     return rb_ary_new4(RSTRUCT_LEN(s), RSTRUCT_PTR(s));
 }
 
+/*
+ *  call-seq:
+ *     struct.to_h     -> hash
+ *
+ *  Returns the values for this instance as a hash with keys
+ *  corresponding to the instance variable name.
+ *
+ *     Customer = Struct.new(:name, :address, :zip)
+ *     joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
+ *     joe.to_h[:address]   #=> "123 Maple, Anytown NC"
+ */
+
+static VALUE
+rb_struct_to_h(VALUE s)
+{
+    VALUE h = rb_hash_new();
+    VALUE members = rb_struct_members(s);
+    long i;
+
+    for (i=0; i<RSTRUCT_LEN(s); i++) {
+	rb_hash_aset(h, rb_ary_entry(members, i), RSTRUCT_PTR(s)[i]);
+    }
+    return h;
+}
+
 /* :nodoc: */
 VALUE
 rb_struct_init_copy(VALUE copy, VALUE s)
@@ -961,6 +986,7 @@
     rb_define_method(rb_cStruct, "inspect", rb_struct_inspect, 0);
     rb_define_alias(rb_cStruct,  "to_s", "inspect");
     rb_define_method(rb_cStruct, "to_a", rb_struct_to_a, 0);
+    rb_define_method(rb_cStruct, "to_h", rb_struct_to_h, 0);
     rb_define_method(rb_cStruct, "values", rb_struct_to_a, 0);
     rb_define_method(rb_cStruct, "size", rb_struct_size, 0);
     rb_define_method(rb_cStruct, "length", rb_struct_size, 0);
Index: NEWS
===================================================================
--- NEWS	(revision 35340)
+++ NEWS	(revision 35341)
@@ -52,6 +52,11 @@
       * Signal.trap raises ArgumentError when :SEGV, :BUS, :ILL, :FPE, :VTALRM
         are specified.
 
+  * Struct
+    * added method:
+      * added Struct#to_h returning values with keys corresponding to the
+        instance variable names.
+
   * Time
     * change return value:
       * Time#to_s returned encoding defaults to US-ASCII but automatically

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

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