From: nobu.nakada@... Date: 2002-01-07T04:54:21+09:00 Subject: [ruby-dev:15645] Enumerable#to_hash (Re: [ruby-talk:30339] Re: OT: Re: Sorting a Hash by value of integer stored in the Hash) なかだです。 At Sun, 6 Jan 2002 19:55:51 +0900, Michal Rokos wrote: > > module Enumerable > > def to_hash(h = {}) > > k = v = nil > > each {|k, v| h[k] = v} > > h > > end > > end > > Yes, sure, but are we able to make it part of STD. Ruby? というわけで、一応こんなのを。 Index: enum.c =================================================================== RCS file: /cvs/ruby/src/ruby/enum.c,v retrieving revision 1.21 diff -u -2 -p -r1.21 enum.c --- enum.c 2001/12/10 07:18:12 1.21 +++ enum.c 2002/01/06 19:53:29 @@ -181,4 +181,33 @@ enum_collect(obj) static VALUE +aset_i(key, hash) + VALUE key, hash; +{ + VALUE val = Qnil; + + if (TYPE(key) == T_ARRAY) { + switch (RARRAY(key)->len) { + default: + val = RARRAY(key)->ptr[1]; + case 1: + key = RARRAY(key)->ptr[0]; + case 0: + } + } + rb_hash_aset(hash, key, val); + return Qnil; +} + +static VALUE +enum_to_hash(obj) + VALUE obj; +{ + VALUE hash = rb_hash_new(); + + rb_iterate(rb_each, obj, aset_i, hash); + return hash; +} + +static VALUE inject_i(i, np) VALUE i; @@ -438,4 +467,5 @@ Init_Enumerable() rb_define_method(rb_mEnumerable,"to_a", enum_to_a, 0); rb_define_method(rb_mEnumerable,"entries", enum_to_a, 0); + rb_define_method(rb_mEnumerable,"to_hash", enum_to_hash, 0); rb_define_method(rb_mEnumerable,"sort", enum_sort, 0); -- --- 僕の前にBugはない。 --- 僕の後ろにBugはできる。 中田 伸悦