summaryrefslogtreecommitdiff
path: root/enum.c
diff options
context:
space:
mode:
authormarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-10-23 15:10:48 +0000
committermarcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2013-10-23 15:10:48 +0000
commitdc215dcd9f96620b7c06a25a741d13b19c2f130b (patch)
tree760deacf8def453cd813b896dbac2b2927f85cf0 /enum.c
parent57e52dea773cd51ed943ae1df142f65b725103a3 (diff)
* 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
Diffstat (limited to 'enum.c')
-rw-r--r--enum.c34
1 files changed, 34 insertions, 0 deletions
diff --git a/enum.c b/enum.c
index df3c5636ec..ce7d22434b 100644
--- a/enum.c
+++ b/enum.c
@@ -510,6 +510,39 @@ enum_to_a(int argc, VALUE *argv, VALUE obj)
}
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 <i>enum</i> as a list of
+ * <tt>[key, value]</tt> 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)
{
NODE *memo = RNODE(p);
@@ -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);