From dc215dcd9f96620b7c06a25a741d13b19c2f130b Mon Sep 17 00:00:00 2001 From: marcandre Date: Wed, 23 Oct 2013 15:10:48 +0000 Subject: * array.c: Add Array#to_h [Feature #7292] * enum.c: Add Enumerable#to_h git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@43401 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- enum.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'enum.c') diff --git a/enum.c b/enum.c index df3c5636ec..ce7d22434b 100644 --- a/enum.c +++ b/enum.c @@ -509,6 +509,39 @@ enum_to_a(int argc, VALUE *argv, VALUE obj) return ary; } +static VALUE +enum_to_h_i(VALUE i, VALUE hash, int argc, VALUE *argv) +{ + ENUM_WANT_SVALUE(); + rb_thread_check_ints(); + i = rb_check_array_type(i); + if (!NIL_P(i) && RARRAY_LEN(i) == 2) { + rb_hash_aset(hash, RARRAY_AREF(i, 0), RARRAY_AREF(i, 1)); + } + return Qnil; +} + +/* + * call-seq: + * enum.to_h(*args) -> hash + * + * Returns the result of interpreting enum as a list of + * [key, value] pairs. Elements other than pairs of + * values are ignored. + * + * %i[hello world].each_with_index.to_h + * # => {:hello => 0, :world => 1} + */ + +static VALUE +enum_to_h(int argc, VALUE *argv, VALUE obj) +{ + VALUE hash = rb_hash_new(); + rb_block_call(obj, id_each, argc, argv, enum_to_h_i, hash); + OBJ_INFECT(hash, obj); + return hash; +} + static VALUE inject_i(VALUE i, VALUE p, int argc, VALUE *argv) { @@ -2758,6 +2791,7 @@ Init_Enumerable(void) rb_define_method(rb_mEnumerable, "to_a", enum_to_a, -1); rb_define_method(rb_mEnumerable, "entries", enum_to_a, -1); + rb_define_method(rb_mEnumerable, "to_h", enum_to_h, -1); rb_define_method(rb_mEnumerable, "sort", enum_sort, 0); rb_define_method(rb_mEnumerable, "sort_by", enum_sort_by, 0); -- cgit v1.2.3