summaryrefslogtreecommitdiff
path: root/struct.c
diff options
context:
space:
mode:
authormarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2012-04-16 03:16:10 +0000
committermarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2012-04-16 03:16:10 +0000
commit1dbe0f0672cfc16c875d0a47bde266ddbaa8ba98 (patch)
treee1830cf693e2c6fae36a7a68dd5bd77ce67d1510 /struct.c
parent33399fe8248a25132343b1b5be3a35357c3d9099 (diff)
* struct.c: Add Struct#to_h [Feature #6276]
[ref #4862] [rubyspec:2082ef46d46e] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@35341 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'struct.c')
-rw-r--r--struct.c26
1 files changed, 26 insertions, 0 deletions
diff --git a/struct.c b/struct.c
index 7fa50f14ee..e958a78df8 100644
--- a/struct.c
+++ b/struct.c
@@ -586,6 +586,31 @@ rb_struct_to_a(VALUE s)
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 @@ Init_Struct(void)
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);