From 770ddcdfe069f8654a07e0fcc758aea591cdd17d Mon Sep 17 00:00:00 2001 From: nobu Date: Tue, 24 Apr 2012 03:46:55 +0000 Subject: * hash.c, object.c, struct.c, lib/ostruct.rb: add to_h methods. [Feature #6276] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@35452 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- struct.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'struct.c') 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