add a comment.
[ruby-svn.git] / hash.c
blob89139e852fc265f2da69cc3e7ff98e9e6d03ddaa
1 /**********************************************************************
3 hash.c -
5 $Author$
6 created at: Mon Nov 22 18:51:18 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/ruby.h"
15 #include "ruby/st.h"
16 #include "ruby/util.h"
17 #include "ruby/signal.h"
19 #ifdef __APPLE__
20 #include <crt_externs.h>
21 #endif
23 static VALUE rb_hash_s_try_convert(VALUE, VALUE);
25 #define HASH_DELETED FL_USER1
26 #define HASH_PROC_DEFAULT FL_USER2
28 VALUE
29 rb_hash_freeze(VALUE hash)
31 return rb_obj_freeze(hash);
34 VALUE rb_cHash;
36 static VALUE envtbl;
37 static ID id_hash, id_yield, id_default;
39 static VALUE
40 eql(VALUE *args)
42 return (VALUE)rb_eql(args[0], args[1]);
45 static int
46 rb_any_cmp(VALUE a, VALUE b)
48 VALUE args[2];
50 if (a == b) return 0;
51 if (FIXNUM_P(a) && FIXNUM_P(b)) {
52 return a != b;
54 if (TYPE(a) == T_STRING && RBASIC(a)->klass == rb_cString &&
55 TYPE(b) == T_STRING && RBASIC(b)->klass == rb_cString) {
56 return rb_str_hash_cmp(a, b);
58 if (a == Qundef || b == Qundef) return -1;
59 if (SYMBOL_P(a) && SYMBOL_P(b)) {
60 return a != b;
63 args[0] = a;
64 args[1] = b;
65 return !rb_with_disable_interrupt(eql, (VALUE)args);
68 VALUE
69 rb_hash(VALUE obj)
71 return rb_funcall(obj, id_hash, 0);
74 static int
75 rb_any_hash(VALUE a)
77 VALUE hval;
78 int hnum;
80 switch (TYPE(a)) {
81 case T_FIXNUM:
82 case T_SYMBOL:
83 hnum = (int)a;
84 break;
86 case T_STRING:
87 hnum = rb_str_hash(a);
88 break;
90 default:
91 hval = rb_funcall(a, id_hash, 0);
92 if (!FIXNUM_P(hval)) {
93 hval = rb_funcall(hval, '%', 1, INT2FIX(536870923));
95 hnum = (int)FIX2LONG(hval);
97 hnum <<= 1;
98 return RSHIFT(hnum, 1);
101 static const struct st_hash_type objhash = {
102 rb_any_cmp,
103 rb_any_hash,
106 static const struct st_hash_type identhash = {
107 st_numcmp,
108 st_numhash,
111 typedef int st_foreach_func(st_data_t, st_data_t, st_data_t);
113 struct foreach_safe_arg {
114 st_table *tbl;
115 st_foreach_func *func;
116 st_data_t arg;
119 static int
120 foreach_safe_i(st_data_t key, st_data_t value, struct foreach_safe_arg *arg)
122 int status;
124 if (key == Qundef) return ST_CONTINUE;
125 status = (*arg->func)(key, value, arg->arg);
126 if (status == ST_CONTINUE) {
127 return ST_CHECK;
129 return status;
132 void
133 st_foreach_safe(st_table *table, int (*func)(ANYARGS), st_data_t a)
135 struct foreach_safe_arg arg;
137 arg.tbl = table;
138 arg.func = (st_foreach_func *)func;
139 arg.arg = a;
140 if (st_foreach(table, foreach_safe_i, (st_data_t)&arg)) {
141 rb_raise(rb_eRuntimeError, "hash modified during iteration");
145 typedef int rb_foreach_func(VALUE, VALUE, VALUE);
147 struct hash_foreach_arg {
148 VALUE hash;
149 rb_foreach_func *func;
150 VALUE arg;
153 static int
154 hash_foreach_iter(VALUE key, VALUE value, struct hash_foreach_arg *arg)
156 int status;
157 st_table *tbl;
159 tbl = RHASH(arg->hash)->ntbl;
160 if (key == Qundef) return ST_CONTINUE;
161 status = (*arg->func)(key, value, arg->arg);
162 if (RHASH(arg->hash)->ntbl != tbl) {
163 rb_raise(rb_eRuntimeError, "rehash occurred during iteration");
165 switch (status) {
166 case ST_DELETE:
167 st_delete_safe(tbl, (st_data_t*)&key, 0, Qundef);
168 FL_SET(arg->hash, HASH_DELETED);
169 case ST_CONTINUE:
170 break;
171 case ST_STOP:
172 return ST_STOP;
174 return ST_CHECK;
177 static VALUE
178 hash_foreach_ensure(VALUE hash)
180 RHASH(hash)->iter_lev--;
182 if (RHASH(hash)->iter_lev == 0) {
183 if (FL_TEST(hash, HASH_DELETED)) {
184 st_cleanup_safe(RHASH(hash)->ntbl, Qundef);
185 FL_UNSET(hash, HASH_DELETED);
188 return 0;
191 static VALUE
192 hash_foreach_call(struct hash_foreach_arg *arg)
194 if (st_foreach(RHASH(arg->hash)->ntbl, hash_foreach_iter, (st_data_t)arg)) {
195 rb_raise(rb_eRuntimeError, "hash modified during iteration");
197 return Qnil;
200 void
201 rb_hash_foreach(VALUE hash, int (*func)(ANYARGS), VALUE farg)
203 struct hash_foreach_arg arg;
205 if (!RHASH(hash)->ntbl)
206 return;
207 RHASH(hash)->iter_lev++;
208 arg.hash = hash;
209 arg.func = (rb_foreach_func *)func;
210 arg.arg = farg;
211 rb_ensure(hash_foreach_call, (VALUE)&arg, hash_foreach_ensure, hash);
214 static VALUE
215 hash_alloc(VALUE klass)
217 NEWOBJ(hash, struct RHash);
218 OBJSETUP(hash, klass, T_HASH);
220 hash->ifnone = Qnil;
222 return (VALUE)hash;
225 VALUE
226 rb_hash_new(void)
228 return hash_alloc(rb_cHash);
231 VALUE
232 rb_hash_dup(VALUE hash)
234 NEWOBJ(ret, struct RHash);
235 DUPSETUP(ret, hash);
237 if (!RHASH_EMPTY_P(hash))
238 ret->ntbl = st_copy(RHASH(hash)->ntbl);
239 if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
240 FL_SET(ret, HASH_PROC_DEFAULT);
242 ret->ifnone = RHASH(hash)->ifnone;
243 return (VALUE)ret;
246 static void
247 rb_hash_modify_check(VALUE hash)
249 if (OBJ_FROZEN(hash)) rb_error_frozen("hash");
250 if (!OBJ_TAINTED(hash) && rb_safe_level() >= 4)
251 rb_raise(rb_eSecurityError, "Insecure: can't modify hash");
254 struct st_table *
255 rb_hash_tbl(VALUE hash)
257 if (!RHASH(hash)->ntbl) {
258 RHASH(hash)->ntbl = st_init_table(&objhash);
260 return RHASH(hash)->ntbl;
263 static void
264 rb_hash_modify(VALUE hash)
266 rb_hash_modify_check(hash);
267 rb_hash_tbl(hash);
271 * call-seq:
272 * Hash.new => hash
273 * Hash.new(obj) => aHash
274 * Hash.new {|hash, key| block } => aHash
276 * Returns a new, empty hash. If this hash is subsequently accessed by
277 * a key that doesn't correspond to a hash entry, the value returned
278 * depends on the style of <code>new</code> used to create the hash. In
279 * the first form, the access returns <code>nil</code>. If
280 * <i>obj</i> is specified, this single object will be used for
281 * all <em>default values</em>. If a block is specified, it will be
282 * called with the hash object and the key, and should return the
283 * default value. It is the block's responsibility to store the value
284 * in the hash if required.
286 * h = Hash.new("Go Fish")
287 * h["a"] = 100
288 * h["b"] = 200
289 * h["a"] #=> 100
290 * h["c"] #=> "Go Fish"
291 * # The following alters the single default object
292 * h["c"].upcase! #=> "GO FISH"
293 * h["d"] #=> "GO FISH"
294 * h.keys #=> ["a", "b"]
296 * # While this creates a new default object each time
297 * h = Hash.new { |hash, key| hash[key] = "Go Fish: #{key}" }
298 * h["c"] #=> "Go Fish: c"
299 * h["c"].upcase! #=> "GO FISH: C"
300 * h["d"] #=> "Go Fish: d"
301 * h.keys #=> ["c", "d"]
305 static VALUE
306 rb_hash_initialize(int argc, VALUE *argv, VALUE hash)
308 VALUE ifnone;
310 rb_hash_modify(hash);
311 if (rb_block_given_p()) {
312 if (argc > 0) {
313 rb_raise(rb_eArgError, "wrong number of arguments");
315 RHASH(hash)->ifnone = rb_block_proc();
316 FL_SET(hash, HASH_PROC_DEFAULT);
318 else {
319 rb_scan_args(argc, argv, "01", &ifnone);
320 RHASH(hash)->ifnone = ifnone;
323 return hash;
327 * call-seq:
328 * Hash[ [key =>|, value]* ] => hash
330 * Creates a new hash populated with the given objects. Equivalent to
331 * the literal <code>{ <i>key</i>, <i>value</i>, ... }</code>. Keys and
332 * values occur in pairs, so there must be an even number of arguments.
334 * Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
335 * Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
336 * { "a" => 100, "b" => 200 } #=> {"a"=>100, "b"=>200}
339 static VALUE
340 rb_hash_s_create(int argc, VALUE *argv, VALUE klass)
342 VALUE hash, tmp;
343 int i;
345 if (argc == 1) {
346 tmp = rb_hash_s_try_convert(Qnil, argv[0]);
347 if (!NIL_P(tmp)) {
348 hash = hash_alloc(klass);
349 if (RHASH(tmp)->ntbl) {
350 RHASH(hash)->ntbl = st_copy(RHASH(tmp)->ntbl);
352 return hash;
355 tmp = rb_check_array_type(argv[0]);
356 if (!NIL_P(tmp)) {
357 long i;
359 hash = hash_alloc(klass);
360 for (i = 0; i < RARRAY_LEN(tmp); ++i) {
361 VALUE v = rb_check_array_type(RARRAY_PTR(tmp)[i]);
363 if (NIL_P(v)) continue;
364 if (RARRAY_LEN(v) < 1 || 2 < RARRAY_LEN(v)) continue;
365 rb_hash_aset(hash, RARRAY_PTR(v)[0], RARRAY_PTR(v)[1]);
367 return hash;
370 if (argc % 2 != 0) {
371 rb_raise(rb_eArgError, "odd number of arguments for Hash");
374 hash = hash_alloc(klass);
375 for (i=0; i<argc; i+=2) {
376 rb_hash_aset(hash, argv[i], argv[i + 1]);
379 return hash;
382 static VALUE
383 to_hash(VALUE hash)
385 return rb_convert_type(hash, T_HASH, "Hash", "to_hash");
389 * call-seq:
390 * Hash.try_convert(obj) -> hash or nil
392 * Try to convert <i>obj</i> into a hash, using to_hash method.
393 * Returns converted hash or nil if <i>obj</i> cannot be converted
394 * for any reason.
396 * Hash.try_convert({1=>2}) # => {1=>2}
397 * Hash.try_convert("1=>2") # => nil
399 static VALUE
400 rb_hash_s_try_convert(VALUE dummy, VALUE hash)
402 return rb_check_convert_type(hash, T_HASH, "Hash", "to_hash");
405 static int
406 rb_hash_rehash_i(VALUE key, VALUE value, st_table *tbl)
408 if (key != Qundef) st_insert(tbl, key, value);
409 return ST_CONTINUE;
413 * call-seq:
414 * hsh.rehash -> hsh
416 * Rebuilds the hash based on the current hash values for each key. If
417 * values of key objects have changed since they were inserted, this
418 * method will reindex <i>hsh</i>. If <code>Hash#rehash</code> is
419 * called while an iterator is traversing the hash, an
420 * <code>RuntimeError</code> will be raised in the iterator.
422 * a = [ "a", "b" ]
423 * c = [ "c", "d" ]
424 * h = { a => 100, c => 300 }
425 * h[a] #=> 100
426 * a[0] = "z"
427 * h[a] #=> nil
428 * h.rehash #=> {["z", "b"]=>100, ["c", "d"]=>300}
429 * h[a] #=> 100
432 static VALUE
433 rb_hash_rehash(VALUE hash)
435 st_table *tbl;
437 if (RHASH(hash)->iter_lev > 0) {
438 rb_raise(rb_eRuntimeError, "rehash during iteration");
440 rb_hash_modify_check(hash);
441 if (!RHASH(hash)->ntbl)
442 return hash;
443 tbl = st_init_table_with_size(RHASH(hash)->ntbl->type, RHASH(hash)->ntbl->num_entries);
444 rb_hash_foreach(hash, rb_hash_rehash_i, (st_data_t)tbl);
445 st_free_table(RHASH(hash)->ntbl);
446 RHASH(hash)->ntbl = tbl;
448 return hash;
452 * call-seq:
453 * hsh[key] => value
455 * Element Reference---Retrieves the <i>value</i> object corresponding
456 * to the <i>key</i> object. If not found, returns the a default value (see
457 * <code>Hash::new</code> for details).
459 * h = { "a" => 100, "b" => 200 }
460 * h["a"] #=> 100
461 * h["c"] #=> nil
465 VALUE
466 rb_hash_aref(VALUE hash, VALUE key)
468 VALUE val;
470 if (!RHASH(hash)->ntbl || !st_lookup(RHASH(hash)->ntbl, key, &val)) {
471 return rb_funcall(hash, id_default, 1, key);
473 return val;
476 VALUE
477 rb_hash_lookup(VALUE hash, VALUE key)
479 VALUE val;
481 if (!RHASH(hash)->ntbl || !st_lookup(RHASH(hash)->ntbl, key, &val)) {
482 return Qnil; /* without Hash#default */
484 return val;
488 * call-seq:
489 * hsh.fetch(key [, default] ) => obj
490 * hsh.fetch(key) {| key | block } => obj
492 * Returns a value from the hash for the given key. If the key can't be
493 * found, there are several options: With no other arguments, it will
494 * raise an <code>KeyError</code> exception; if <i>default</i> is
495 * given, then that will be returned; if the optional code block is
496 * specified, then that will be run and its result returned.
498 * h = { "a" => 100, "b" => 200 }
499 * h.fetch("a") #=> 100
500 * h.fetch("z", "go fish") #=> "go fish"
501 * h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z"
503 * The following example shows that an exception is raised if the key
504 * is not found and a default value is not supplied.
506 * h = { "a" => 100, "b" => 200 }
507 * h.fetch("z")
509 * <em>produces:</em>
511 * prog.rb:2:in `fetch': key not found (KeyError)
512 * from prog.rb:2
516 static VALUE
517 rb_hash_fetch(int argc, VALUE *argv, VALUE hash)
519 VALUE key, if_none;
520 VALUE val;
521 long block_given;
523 rb_scan_args(argc, argv, "11", &key, &if_none);
525 block_given = rb_block_given_p();
526 if (block_given && argc == 2) {
527 rb_warn("block supersedes default value argument");
529 if (!RHASH(hash)->ntbl || !st_lookup(RHASH(hash)->ntbl, key, &val)) {
530 if (block_given) return rb_yield(key);
531 if (argc == 1) {
532 rb_raise(rb_eKeyError, "key not found");
534 return if_none;
536 return val;
540 * call-seq:
541 * hsh.default(key=nil) => obj
543 * Returns the default value, the value that would be returned by
544 * <i>hsh</i>[<i>key</i>] if <i>key</i> did not exist in <i>hsh</i>.
545 * See also <code>Hash::new</code> and <code>Hash#default=</code>.
547 * h = Hash.new #=> {}
548 * h.default #=> nil
549 * h.default(2) #=> nil
551 * h = Hash.new("cat") #=> {}
552 * h.default #=> "cat"
553 * h.default(2) #=> "cat"
555 * h = Hash.new {|h,k| h[k] = k.to_i*10} #=> {}
556 * h.default #=> nil
557 * h.default(2) #=> 20
560 static VALUE
561 rb_hash_default(int argc, VALUE *argv, VALUE hash)
563 VALUE key;
565 rb_scan_args(argc, argv, "01", &key);
566 if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
567 if (argc == 0) return Qnil;
568 return rb_funcall(RHASH(hash)->ifnone, id_yield, 2, hash, key);
570 return RHASH(hash)->ifnone;
574 * call-seq:
575 * hsh.default = obj => hsh
577 * Sets the default value, the value returned for a key that does not
578 * exist in the hash. It is not possible to set the a default to a
579 * <code>Proc</code> that will be executed on each key lookup.
581 * h = { "a" => 100, "b" => 200 }
582 * h.default = "Go fish"
583 * h["a"] #=> 100
584 * h["z"] #=> "Go fish"
585 * # This doesn't do what you might hope...
586 * h.default = proc do |hash, key|
587 * hash[key] = key + key
588 * end
589 * h[2] #=> #<Proc:0x401b3948@-:6>
590 * h["cat"] #=> #<Proc:0x401b3948@-:6>
593 static VALUE
594 rb_hash_set_default(VALUE hash, VALUE ifnone)
596 rb_hash_modify(hash);
597 RHASH(hash)->ifnone = ifnone;
598 FL_UNSET(hash, HASH_PROC_DEFAULT);
599 return ifnone;
603 * call-seq:
604 * hsh.default_proc -> anObject
606 * If <code>Hash::new</code> was invoked with a block, return that
607 * block, otherwise return <code>nil</code>.
609 * h = Hash.new {|h,k| h[k] = k*k } #=> {}
610 * p = h.default_proc #=> #<Proc:0x401b3d08@-:1>
611 * a = [] #=> []
612 * p.call(a, 2)
613 * a #=> [nil, nil, 4]
617 static VALUE
618 rb_hash_default_proc(VALUE hash)
620 if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
621 return RHASH(hash)->ifnone;
623 return Qnil;
626 static int
627 key_i(VALUE key, VALUE value, VALUE *args)
629 if (rb_equal(value, args[0])) {
630 args[1] = key;
631 return ST_STOP;
633 return ST_CONTINUE;
637 * call-seq:
638 * hsh.key(value) => key
640 * Returns the key for a given value. If not found, returns <code>nil</code>.
642 * h = { "a" => 100, "b" => 200 }
643 * h.key(200) #=> "b"
644 * h.key(999) #=> nil
648 static VALUE
649 rb_hash_key(VALUE hash, VALUE value)
651 VALUE args[2];
653 args[0] = value;
654 args[1] = Qnil;
656 rb_hash_foreach(hash, key_i, (st_data_t)args);
658 return args[1];
661 /* :nodoc: */
662 static VALUE
663 rb_hash_index(VALUE hash, VALUE value)
665 rb_warn("Hash#index is deprecated; use Hash#key");
666 return rb_hash_key(hash, value);
669 static VALUE
670 rb_hash_delete_key(VALUE hash, VALUE key)
672 st_data_t ktmp = (st_data_t)key, val;
674 if (!RHASH(hash)->ntbl)
675 return Qundef;
676 if (RHASH(hash)->iter_lev > 0) {
677 if (st_delete_safe(RHASH(hash)->ntbl, &ktmp, &val, Qundef)) {
678 FL_SET(hash, HASH_DELETED);
679 return (VALUE)val;
682 else if (st_delete(RHASH(hash)->ntbl, &ktmp, &val))
683 return (VALUE)val;
684 return Qundef;
688 * call-seq:
689 * hsh.delete(key) => value
690 * hsh.delete(key) {| key | block } => value
692 * Deletes and returns a key-value pair from <i>hsh</i> whose key is
693 * equal to <i>key</i>. If the key is not found, returns the
694 * <em>default value</em>. If the optional code block is given and the
695 * key is not found, pass in the key and return the result of
696 * <i>block</i>.
698 * h = { "a" => 100, "b" => 200 }
699 * h.delete("a") #=> 100
700 * h.delete("z") #=> nil
701 * h.delete("z") { |el| "#{el} not found" } #=> "z not found"
705 VALUE
706 rb_hash_delete(VALUE hash, VALUE key)
708 VALUE val;
710 rb_hash_modify(hash);
711 val = rb_hash_delete_key(hash, key);
712 if (val != Qundef) return val;
713 if (rb_block_given_p()) {
714 return rb_yield(key);
716 return Qnil;
719 struct shift_var {
720 VALUE key;
721 VALUE val;
724 static int
725 shift_i(VALUE key, VALUE value, struct shift_var *var)
727 if (key == Qundef) return ST_CONTINUE;
728 if (var->key != Qundef) return ST_STOP;
729 var->key = key;
730 var->val = value;
731 return ST_DELETE;
734 static int
735 shift_i_safe(VALUE key, VALUE value, struct shift_var *var)
737 if (key == Qundef) return ST_CONTINUE;
738 var->key = key;
739 var->val = value;
740 return ST_STOP;
744 * call-seq:
745 * hsh.shift -> anArray or obj
747 * Removes a key-value pair from <i>hsh</i> and returns it as the
748 * two-item array <code>[</code> <i>key, value</i> <code>]</code>, or
749 * the hash's default value if the hash is empty.
751 * h = { 1 => "a", 2 => "b", 3 => "c" }
752 * h.shift #=> [1, "a"]
753 * h #=> {2=>"b", 3=>"c"}
756 static VALUE
757 rb_hash_shift(VALUE hash)
759 struct shift_var var;
761 rb_hash_modify(hash);
762 var.key = Qundef;
763 rb_hash_foreach(hash, RHASH(hash)->iter_lev > 0 ? shift_i_safe : shift_i,
764 (st_data_t)&var);
766 if (var.key != Qundef) {
767 if (RHASH(hash)->iter_lev > 0) {
768 rb_hash_delete_key(hash, var.key);
770 return rb_assoc_new(var.key, var.val);
772 else if (FL_TEST(hash, HASH_PROC_DEFAULT)) {
773 return rb_funcall(RHASH(hash)->ifnone, id_yield, 2, hash, Qnil);
775 else {
776 return RHASH(hash)->ifnone;
780 static int
781 delete_if_i(VALUE key, VALUE value, VALUE hash)
783 if (key == Qundef) return ST_CONTINUE;
784 if (RTEST(rb_yield_values(2, key, value))) {
785 rb_hash_delete_key(hash, key);
787 return ST_CONTINUE;
791 * call-seq:
792 * hsh.delete_if {| key, value | block } -> hsh
794 * Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
795 * evaluates to <code>true</code>.
797 * h = { "a" => 100, "b" => 200, "c" => 300 }
798 * h.delete_if {|key, value| key >= "b" } #=> {"a"=>100}
802 VALUE
803 rb_hash_delete_if(VALUE hash)
805 RETURN_ENUMERATOR(hash, 0, 0);
806 rb_hash_modify(hash);
807 rb_hash_foreach(hash, delete_if_i, hash);
808 return hash;
812 * call-seq:
813 * hsh.reject! {| key, value | block } -> hsh or nil
815 * Equivalent to <code>Hash#delete_if</code>, but returns
816 * <code>nil</code> if no changes were made.
819 VALUE
820 rb_hash_reject_bang(VALUE hash)
822 int n;
824 RETURN_ENUMERATOR(hash, 0, 0);
825 if (!RHASH(hash)->ntbl)
826 return Qnil;
827 n = RHASH(hash)->ntbl->num_entries;
828 rb_hash_delete_if(hash);
829 if (n == RHASH(hash)->ntbl->num_entries) return Qnil;
830 return hash;
834 * call-seq:
835 * hsh.reject {| key, value | block } -> a_hash
837 * Same as <code>Hash#delete_if</code>, but works on (and returns) a
838 * copy of the <i>hsh</i>. Equivalent to
839 * <code><i>hsh</i>.dup.delete_if</code>.
843 static VALUE
844 rb_hash_reject(VALUE hash)
846 return rb_hash_delete_if(rb_obj_dup(hash));
850 * call-seq:
851 * hsh.values_at(key, ...) => array
853 * Return an array containing the values associated with the given keys.
854 * Also see <code>Hash.select</code>.
856 * h = { "cat" => "feline", "dog" => "canine", "cow" => "bovine" }
857 * h.values_at("cow", "cat") #=> ["bovine", "feline"]
860 VALUE
861 rb_hash_values_at(int argc, VALUE *argv, VALUE hash)
863 VALUE result = rb_ary_new2(argc);
864 long i;
866 for (i=0; i<argc; i++) {
867 rb_ary_push(result, rb_hash_aref(hash, argv[i]));
869 return result;
872 static int
873 select_i(VALUE key, VALUE value, VALUE result)
875 if (key == Qundef) return ST_CONTINUE;
876 if (RTEST(rb_yield_values(2, key, value)))
877 rb_hash_aset(result, key, value);
878 return ST_CONTINUE;
882 * call-seq:
883 * hsh.select {|key, value| block} => a_hash
885 * Returns a new hash consisting of entries which the block returns true.
887 * h = { "a" => 100, "b" => 200, "c" => 300 }
888 * h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
889 * h.select {|k,v| v < 200} #=> {"a" => 100}
892 VALUE
893 rb_hash_select(VALUE hash)
895 VALUE result;
897 RETURN_ENUMERATOR(hash, 0, 0);
898 result = rb_hash_new();
899 rb_hash_foreach(hash, select_i, result);
900 return result;
903 static int
904 clear_i(VALUE key, VALUE value, VALUE dummy)
906 return ST_DELETE;
910 * call-seq:
911 * hsh.clear -> hsh
913 * Removes all key-value pairs from <i>hsh</i>.
915 * h = { "a" => 100, "b" => 200 } #=> {"a"=>100, "b"=>200}
916 * h.clear #=> {}
920 static VALUE
921 rb_hash_clear(VALUE hash)
923 rb_hash_modify_check(hash);
924 if (!RHASH(hash)->ntbl)
925 return hash;
926 if (RHASH(hash)->ntbl->num_entries > 0) {
927 if (RHASH(hash)->iter_lev > 0)
928 rb_hash_foreach(hash, clear_i, 0);
929 else
930 st_clear(RHASH(hash)->ntbl);
933 return hash;
937 * call-seq:
938 * hsh[key] = value => value
939 * hsh.store(key, value) => value
941 * Element Assignment---Associates the value given by
942 * <i>value</i> with the key given by <i>key</i>.
943 * <i>key</i> should not have its value changed while it is in
944 * use as a key (a <code>String</code> passed as a key will be
945 * duplicated and frozen).
947 * h = { "a" => 100, "b" => 200 }
948 * h["a"] = 9
949 * h["c"] = 4
950 * h #=> {"a"=>9, "b"=>200, "c"=>4}
954 VALUE
955 rb_hash_aset(VALUE hash, VALUE key, VALUE val)
957 rb_hash_modify(hash);
958 if (RHASH(hash)->ntbl->type == &identhash ||
959 TYPE(key) != T_STRING || st_lookup(RHASH(hash)->ntbl, key, 0)) {
960 st_insert(RHASH(hash)->ntbl, key, val);
962 else {
963 st_add_direct(RHASH(hash)->ntbl, rb_str_new4(key), val);
965 return val;
968 static int
969 replace_i(VALUE key, VALUE val, VALUE hash)
971 if (key != Qundef) {
972 rb_hash_aset(hash, key, val);
975 return ST_CONTINUE;
979 * call-seq:
980 * hsh.replace(other_hash) -> hsh
982 * Replaces the contents of <i>hsh</i> with the contents of
983 * <i>other_hash</i>.
985 * h = { "a" => 100, "b" => 200 }
986 * h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
990 static VALUE
991 rb_hash_replace(VALUE hash, VALUE hash2)
993 hash2 = to_hash(hash2);
994 if (hash == hash2) return hash;
995 rb_hash_clear(hash);
996 rb_hash_foreach(hash2, replace_i, hash);
997 RHASH(hash)->ifnone = RHASH(hash2)->ifnone;
998 if (FL_TEST(hash2, HASH_PROC_DEFAULT)) {
999 FL_SET(hash, HASH_PROC_DEFAULT);
1001 else {
1002 FL_UNSET(hash, HASH_PROC_DEFAULT);
1005 return hash;
1009 * call-seq:
1010 * hsh.length => fixnum
1011 * hsh.size => fixnum
1013 * Returns the number of key-value pairs in the hash.
1015 * h = { "d" => 100, "a" => 200, "v" => 300, "e" => 400 }
1016 * h.length #=> 4
1017 * h.delete("a") #=> 200
1018 * h.length #=> 3
1021 static VALUE
1022 rb_hash_size(VALUE hash)
1024 if (!RHASH(hash)->ntbl)
1025 return INT2FIX(0);
1026 return INT2FIX(RHASH(hash)->ntbl->num_entries);
1031 * call-seq:
1032 * hsh.empty? => true or false
1034 * Returns <code>true</code> if <i>hsh</i> contains no key-value pairs.
1036 * {}.empty? #=> true
1040 static VALUE
1041 rb_hash_empty_p(VALUE hash)
1043 return RHASH_EMPTY_P(hash) ? Qtrue : Qfalse;
1046 static int
1047 each_value_i(VALUE key, VALUE value)
1049 if (key == Qundef) return ST_CONTINUE;
1050 rb_yield(value);
1051 return ST_CONTINUE;
1055 * call-seq:
1056 * hsh.each_value {| value | block } -> hsh
1058 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the
1059 * value as a parameter.
1061 * h = { "a" => 100, "b" => 200 }
1062 * h.each_value {|value| puts value }
1064 * <em>produces:</em>
1066 * 100
1067 * 200
1070 static VALUE
1071 rb_hash_each_value(VALUE hash)
1073 RETURN_ENUMERATOR(hash, 0, 0);
1074 rb_hash_foreach(hash, each_value_i, 0);
1075 return hash;
1078 static int
1079 each_key_i(VALUE key, VALUE value)
1081 if (key == Qundef) return ST_CONTINUE;
1082 rb_yield(key);
1083 return ST_CONTINUE;
1087 * call-seq:
1088 * hsh.each_key {| key | block } -> hsh
1090 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key
1091 * as a parameter.
1093 * h = { "a" => 100, "b" => 200 }
1094 * h.each_key {|key| puts key }
1096 * <em>produces:</em>
1101 static VALUE
1102 rb_hash_each_key(VALUE hash)
1104 RETURN_ENUMERATOR(hash, 0, 0);
1105 rb_hash_foreach(hash, each_key_i, 0);
1106 return hash;
1109 static int
1110 each_pair_i(VALUE key, VALUE value)
1112 if (key == Qundef) return ST_CONTINUE;
1113 rb_yield(rb_assoc_new(key, value));
1114 return ST_CONTINUE;
1118 * call-seq:
1119 * hsh.each {| key, value | block } -> hsh
1120 * hsh.each_pair {| key, value | block } -> hsh
1122 * Calls <i>block</i> once for each key in <i>hsh</i>, passing the key-value
1123 * pair as parameters.
1125 * h = { "a" => 100, "b" => 200 }
1126 * h.each {|key, value| puts "#{key} is #{value}" }
1128 * <em>produces:</em>
1130 * a is 100
1131 * b is 200
1135 static VALUE
1136 rb_hash_each_pair(VALUE hash)
1138 RETURN_ENUMERATOR(hash, 0, 0);
1139 rb_hash_foreach(hash, each_pair_i, 0);
1140 return hash;
1143 static int
1144 to_a_i(VALUE key, VALUE value, VALUE ary)
1146 if (key == Qundef) return ST_CONTINUE;
1147 rb_ary_push(ary, rb_assoc_new(key, value));
1148 return ST_CONTINUE;
1152 * call-seq:
1153 * hsh.to_a -> array
1155 * Converts <i>hsh</i> to a nested array of <code>[</code> <i>key,
1156 * value</i> <code>]</code> arrays.
1158 * h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
1159 * h.to_a #=> [["c", 300], ["a", 100], ["d", 400]]
1162 static VALUE
1163 rb_hash_to_a(VALUE hash)
1165 VALUE ary;
1167 ary = rb_ary_new();
1168 rb_hash_foreach(hash, to_a_i, ary);
1169 if (OBJ_TAINTED(hash)) OBJ_TAINT(ary);
1171 return ary;
1174 static int
1175 inspect_i(VALUE key, VALUE value, VALUE str)
1177 VALUE str2;
1179 if (key == Qundef) return ST_CONTINUE;
1180 if (RSTRING_LEN(str) > 1) {
1181 rb_str_cat2(str, ", ");
1183 str2 = rb_inspect(key);
1184 rb_str_buf_append(str, str2);
1185 OBJ_INFECT(str, str2);
1186 rb_str_buf_cat2(str, "=>");
1187 str2 = rb_inspect(value);
1188 rb_str_buf_append(str, str2);
1189 OBJ_INFECT(str, str2);
1191 return ST_CONTINUE;
1194 static VALUE
1195 inspect_hash(VALUE hash, VALUE dummy, int recur)
1197 VALUE str;
1199 if (recur) return rb_usascii_str_new2("{...}");
1200 str = rb_str_buf_new2("{");
1201 rb_hash_foreach(hash, inspect_i, str);
1202 rb_str_buf_cat2(str, "}");
1203 OBJ_INFECT(str, hash);
1205 return str;
1209 * call-seq:
1210 * hsh.to_s => string
1211 * hsh.inspect => string
1213 * Return the contents of this hash as a string.
1215 * h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
1216 * h.to_s #=> "{\"c\"=>300, \"a\"=>100, \"d\"=>400}"
1219 static VALUE
1220 rb_hash_inspect(VALUE hash)
1222 if (RHASH_EMPTY_P(hash))
1223 return rb_usascii_str_new2("{}");
1224 return rb_exec_recursive(inspect_hash, hash, 0);
1228 * call-seq:
1229 * hsh.to_hash => hsh
1231 * Returns <i>self</i>.
1234 static VALUE
1235 rb_hash_to_hash(VALUE hash)
1237 return hash;
1240 static int
1241 keys_i(VALUE key, VALUE value, VALUE ary)
1243 if (key == Qundef) return ST_CONTINUE;
1244 rb_ary_push(ary, key);
1245 return ST_CONTINUE;
1249 * call-seq:
1250 * hsh.keys => array
1252 * Returns a new array populated with the keys from this hash. See also
1253 * <code>Hash#values</code>.
1255 * h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 }
1256 * h.keys #=> ["a", "b", "c", "d"]
1260 static VALUE
1261 rb_hash_keys(VALUE hash)
1263 VALUE ary;
1265 ary = rb_ary_new();
1266 rb_hash_foreach(hash, keys_i, ary);
1268 return ary;
1271 static int
1272 values_i(VALUE key, VALUE value, VALUE ary)
1274 if (key == Qundef) return ST_CONTINUE;
1275 rb_ary_push(ary, value);
1276 return ST_CONTINUE;
1280 * call-seq:
1281 * hsh.values => array
1283 * Returns a new array populated with the values from <i>hsh</i>. See
1284 * also <code>Hash#keys</code>.
1286 * h = { "a" => 100, "b" => 200, "c" => 300 }
1287 * h.values #=> [100, 200, 300]
1291 static VALUE
1292 rb_hash_values(VALUE hash)
1294 VALUE ary;
1296 ary = rb_ary_new();
1297 rb_hash_foreach(hash, values_i, ary);
1299 return ary;
1303 * call-seq:
1304 * hsh.has_key?(key) => true or false
1305 * hsh.include?(key) => true or false
1306 * hsh.key?(key) => true or false
1307 * hsh.member?(key) => true or false
1309 * Returns <code>true</code> if the given key is present in <i>hsh</i>.
1311 * h = { "a" => 100, "b" => 200 }
1312 * h.has_key?("a") #=> true
1313 * h.has_key?("z") #=> false
1317 static VALUE
1318 rb_hash_has_key(VALUE hash, VALUE key)
1320 if (!RHASH(hash)->ntbl)
1321 return Qfalse;
1322 if (st_lookup(RHASH(hash)->ntbl, key, 0)) {
1323 return Qtrue;
1325 return Qfalse;
1328 static int
1329 rb_hash_search_value(VALUE key, VALUE value, VALUE *data)
1331 if (key == Qundef) return ST_CONTINUE;
1332 if (rb_equal(value, data[1])) {
1333 data[0] = Qtrue;
1334 return ST_STOP;
1336 return ST_CONTINUE;
1340 * call-seq:
1341 * hsh.has_value?(value) => true or false
1342 * hsh.value?(value) => true or false
1344 * Returns <code>true</code> if the given value is present for some key
1345 * in <i>hsh</i>.
1347 * h = { "a" => 100, "b" => 200 }
1348 * h.has_value?(100) #=> true
1349 * h.has_value?(999) #=> false
1352 static VALUE
1353 rb_hash_has_value(VALUE hash, VALUE val)
1355 VALUE data[2];
1357 data[0] = Qfalse;
1358 data[1] = val;
1359 rb_hash_foreach(hash, rb_hash_search_value, (st_data_t)data);
1360 return data[0];
1363 struct equal_data {
1364 VALUE result;
1365 st_table *tbl;
1366 int eql;
1369 static int
1370 eql_i(VALUE key, VALUE val1, struct equal_data *data)
1372 VALUE val2;
1374 if (key == Qundef) return ST_CONTINUE;
1375 if (!st_lookup(data->tbl, key, &val2)) {
1376 data->result = Qfalse;
1377 return ST_STOP;
1379 if (!(data->eql ? rb_eql(val1, val2) : rb_equal(val1, val2))) {
1380 data->result = Qfalse;
1381 return ST_STOP;
1383 return ST_CONTINUE;
1386 static VALUE
1387 recursive_eql(VALUE hash, VALUE dt, int recur)
1389 struct equal_data *data;
1391 if (recur) return Qfalse;
1392 data = (struct equal_data*)dt;
1393 data->result = Qtrue;
1394 rb_hash_foreach(hash, eql_i, (st_data_t)data);
1396 return data->result;
1399 static VALUE
1400 hash_equal(VALUE hash1, VALUE hash2, int eql)
1402 struct equal_data data;
1404 if (hash1 == hash2) return Qtrue;
1405 if (TYPE(hash2) != T_HASH) {
1406 if (!rb_respond_to(hash2, rb_intern("to_hash"))) {
1407 return Qfalse;
1409 if (eql)
1410 return rb_eql(hash2, hash1);
1411 else
1412 return rb_equal(hash2, hash1);
1414 if (RHASH_SIZE(hash1) != RHASH_SIZE(hash2))
1415 return Qfalse;
1416 if (!RHASH(hash1)->ntbl || !RHASH(hash2)->ntbl)
1417 return Qtrue;
1418 if (RHASH(hash1)->ntbl->type != RHASH(hash2)->ntbl->type)
1419 return Qfalse;
1420 #if 0
1421 if (!(rb_equal(RHASH(hash1)->ifnone, RHASH(hash2)->ifnone) &&
1422 FL_TEST(hash1, HASH_PROC_DEFAULT) == FL_TEST(hash2, HASH_PROC_DEFAULT)))
1423 return Qfalse;
1424 #endif
1426 data.tbl = RHASH(hash2)->ntbl;
1427 data.eql = eql;
1428 return rb_exec_recursive(recursive_eql, hash1, (VALUE)&data);
1432 * call-seq:
1433 * hsh == other_hash => true or false
1435 * Equality---Two hashes are equal if they each contain the same number
1436 * of keys and if each key-value pair is equal to (according to
1437 * <code>Object#==</code>) the corresponding elements in the other
1438 * hash.
1440 * h1 = { "a" => 1, "c" => 2 }
1441 * h2 = { 7 => 35, "c" => 2, "a" => 1 }
1442 * h3 = { "a" => 1, "c" => 2, 7 => 35 }
1443 * h4 = { "a" => 1, "d" => 2, "f" => 35 }
1444 * h1 == h2 #=> false
1445 * h2 == h3 #=> true
1446 * h3 == h4 #=> false
1450 static VALUE
1451 rb_hash_equal(VALUE hash1, VALUE hash2)
1453 return hash_equal(hash1, hash2, Qfalse);
1457 * call-seq:
1458 * hash.eql?(other) -> true or false
1460 * Returns <code>true</code> if <i>hash</i> and <i>other</i> are
1461 * both hashes with the same content.
1464 static VALUE
1465 rb_hash_eql(VALUE hash1, VALUE hash2)
1467 return hash_equal(hash1, hash2, Qtrue);
1470 static int
1471 hash_i(VALUE key, VALUE val, int *hval)
1473 if (key == Qundef) return ST_CONTINUE;
1474 *hval ^= rb_hash(key);
1475 *hval ^= rb_hash(val);
1476 return ST_CONTINUE;
1479 static VALUE
1480 recursive_hash(VALUE hash, VALUE dummy, int recur)
1482 int hval;
1484 if (recur) {
1485 return LONG2FIX(0);
1487 if (!RHASH(hash)->ntbl)
1488 return LONG2FIX(0);
1489 hval = RHASH(hash)->ntbl->num_entries;
1490 rb_hash_foreach(hash, hash_i, (st_data_t)&hval);
1491 return INT2FIX(hval);
1495 * call-seq:
1496 * array.hash -> fixnum
1498 * Compute a hash-code for this array. Two arrays with the same content
1499 * will have the same hash code (and will compare using <code>eql?</code>).
1502 static VALUE
1503 rb_hash_hash(VALUE hash)
1505 return rb_exec_recursive(recursive_hash, hash, 0);
1508 static int
1509 rb_hash_invert_i(VALUE key, VALUE value, VALUE hash)
1511 if (key == Qundef) return ST_CONTINUE;
1512 rb_hash_aset(hash, value, key);
1513 return ST_CONTINUE;
1517 * call-seq:
1518 * hsh.invert -> aHash
1520 * Returns a new hash created by using <i>hsh</i>'s values as keys, and
1521 * the keys as values.
1523 * h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
1524 * h.invert #=> {0=>"a", 100=>"m", 200=>"d", 300=>"y"}
1528 static VALUE
1529 rb_hash_invert(VALUE hash)
1531 VALUE h = rb_hash_new();
1533 rb_hash_foreach(hash, rb_hash_invert_i, h);
1534 return h;
1537 static int
1538 rb_hash_update_i(VALUE key, VALUE value, VALUE hash)
1540 if (key == Qundef) return ST_CONTINUE;
1541 rb_hash_aset(hash, key, value);
1542 return ST_CONTINUE;
1545 static int
1546 rb_hash_update_block_i(VALUE key, VALUE value, VALUE hash)
1548 if (key == Qundef) return ST_CONTINUE;
1549 if (rb_hash_has_key(hash, key)) {
1550 value = rb_yield_values(3, key, rb_hash_aref(hash, key), value);
1552 rb_hash_aset(hash, key, value);
1553 return ST_CONTINUE;
1557 * call-seq:
1558 * hsh.merge!(other_hash) => hsh
1559 * hsh.update(other_hash) => hsh
1560 * hsh.merge!(other_hash){|key, oldval, newval| block} => hsh
1561 * hsh.update(other_hash){|key, oldval, newval| block} => hsh
1563 * Adds the contents of <i>other_hash</i> to <i>hsh</i>. If no
1564 * block is specified entries with duplicate keys are overwritten
1565 * with the values from <i>other_hash</i>, otherwise the value
1566 * of each duplicate key is determined by calling the block with
1567 * the key, its value in <i>hsh</i> and its value in <i>other_hash</i>.
1569 * h1 = { "a" => 100, "b" => 200 }
1570 * h2 = { "b" => 254, "c" => 300 }
1571 * h1.merge!(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1573 * h1 = { "a" => 100, "b" => 200 }
1574 * h2 = { "b" => 254, "c" => 300 }
1575 * h1.merge!(h2) { |key, v1, v2| v1 }
1576 * #=> {"a"=>100, "b"=>200, "c"=>300}
1579 static VALUE
1580 rb_hash_update(VALUE hash1, VALUE hash2)
1582 hash2 = to_hash(hash2);
1583 if (rb_block_given_p()) {
1584 rb_hash_foreach(hash2, rb_hash_update_block_i, hash1);
1586 else {
1587 rb_hash_foreach(hash2, rb_hash_update_i, hash1);
1589 return hash1;
1593 * call-seq:
1594 * hsh.merge(other_hash) -> a_hash
1595 * hsh.merge(other_hash){|key, oldval, newval| block} -> a_hash
1597 * Returns a new hash containing the contents of <i>other_hash</i> and
1598 * the contents of <i>hsh</i>, overwriting entries in <i>hsh</i> with
1599 * duplicate keys with those from <i>other_hash</i>.
1601 * h1 = { "a" => 100, "b" => 200 }
1602 * h2 = { "b" => 254, "c" => 300 }
1603 * h1.merge(h2) #=> {"a"=>100, "b"=>254, "c"=>300}
1604 * h1 #=> {"a"=>100, "b"=>200}
1608 static VALUE
1609 rb_hash_merge(VALUE hash1, VALUE hash2)
1611 return rb_hash_update(rb_obj_dup(hash1), hash2);
1614 static int
1615 assoc_i(VALUE key, VALUE val, VALUE *args)
1617 if (key == Qundef) return ST_CONTINUE;
1618 if (RTEST(rb_equal(args[0], key))) {
1619 args[1] = rb_assoc_new(key, val);
1620 return ST_STOP;
1622 return ST_CONTINUE;
1626 * call-seq:
1627 * hash.assoc(obj) -> an_array or nil
1629 * Searches through the hash comparing _obj_ with the key using <code>==</code>.
1630 * Returns the key-value pair (two elements array) or +nil+
1631 * if no match is found. See <code>Array#assoc</code>.
1633 * h = {"colors" => ["red", "blue", "green"],
1634 * "letters" => ["a", "b", "c" ]}
1635 * h.assoc("letters") #=> ["letters", ["a", "b", "c"]]
1636 * h.assoc("foo") #=> nil
1639 VALUE
1640 rb_hash_assoc(VALUE hash, VALUE obj)
1642 VALUE args[2];
1644 args[0] = obj;
1645 args[1] = Qnil;
1646 rb_hash_foreach(hash, assoc_i, (st_data_t)args);
1647 return args[1];
1650 static int
1651 rassoc_i(VALUE key, VALUE val, VALUE *args)
1653 if (key == Qundef) return ST_CONTINUE;
1654 if (RTEST(rb_equal(args[0], val))) {
1655 args[1] = rb_assoc_new(key, val);
1656 return ST_STOP;
1658 return ST_CONTINUE;
1662 * call-seq:
1663 * hash.rassoc(key) -> an_array or nil
1665 * Searches through the hash comparing _obj_ with the value using <code>==</code>.
1666 * Returns the first key-value pair (two elements array) that matches. See
1667 * also <code>Array#rassoc</code>.
1669 * a = {1=> "one", 2 => "two", 3 => "three", "ii" => "two"}
1670 * a.rassoc("two") #=> [2, "two"]
1671 * a.rassoc("four") #=> nil
1674 VALUE
1675 rb_hash_rassoc(VALUE hash, VALUE obj)
1677 VALUE args[2];
1679 args[0] = obj;
1680 args[1] = Qnil;
1681 rb_hash_foreach(hash, rassoc_i, (st_data_t)args);
1682 return args[1];
1686 * call-seq:
1687 * hash.flatten -> an_array
1688 * hash.flatten(level) -> an_array
1690 * Returns a new array that is a one-dimensional flattening of this
1691 * hash. That is, for every key or value that is an array, extract
1692 * its elements into the new array. Unlike Array#flatten, this
1693 * method does not flatten recursively by default. If the optional
1694 * <i>level</i> argument determines the level of recursion to flatten.
1696 * a = {1=> "one", 2 => [2,"two"], 3 => "three"}
1697 * a.flatten # => [1, "one", 2, [2, "two"], 3, "three"]
1698 * a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"]
1701 static VALUE
1702 rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
1704 VALUE ary, tmp;
1706 ary = rb_hash_to_a(hash);
1707 if (argc == 0) {
1708 argc = 1;
1709 tmp = INT2FIX(1);
1710 argv = &tmp;
1712 rb_funcall2(ary, rb_intern("flatten!"), argc, argv);
1713 return ary;
1717 * call-seq:
1718 * hsh.compare_by_identity => hsh
1720 * Makes <i>hsh</i> to compare its keys by their identity, i.e. it
1721 * will consider exact same objects as same keys.
1723 * h1 = { "a" => 100, "b" => 200, :c => "c" }
1724 * h1["a"] #=> 100
1725 * h1.compare_by_identity
1726 * h1.compare_by_identity? #=> true
1727 * h1["a"] #=> nil # different objects.
1728 * h1[:c] #=> "c" # same symbols are all same.
1732 static VALUE
1733 rb_hash_compare_by_id(VALUE hash)
1735 rb_hash_modify(hash);
1736 RHASH(hash)->ntbl->type = &identhash;
1737 rb_hash_rehash(hash);
1738 return hash;
1742 * call-seq:
1743 * hsh.compare_by_identity? => true or false
1745 * Returns <code>true</code> if <i>hsh</i> will compare its keys by
1746 * their identity. Also see <code>Hash#compare_by_identity</code>.
1750 static VALUE
1751 rb_hash_compare_by_id_p(VALUE hash)
1753 if (!RHASH(hash)->ntbl)
1754 return Qfalse;
1755 if (RHASH(hash)->ntbl->type == &identhash) {
1756 return Qtrue;
1758 return Qfalse;
1761 static int path_tainted = -1;
1763 static char **origenviron;
1764 #ifdef _WIN32
1765 #define GET_ENVIRON(e) (e = rb_w32_get_environ())
1766 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
1767 static char **my_environ;
1768 #undef environ
1769 #define environ my_environ
1770 #elif defined(__APPLE__)
1771 #undef environ
1772 #define environ (*_NSGetEnviron())
1773 #define GET_ENVIRON(e) (e)
1774 #define FREE_ENVIRON(e)
1775 #else
1776 extern char **environ;
1777 #define GET_ENVIRON(e) (e)
1778 #define FREE_ENVIRON(e)
1779 #endif
1781 static VALUE
1782 env_str_new(const char *ptr, long len)
1784 VALUE str = rb_tainted_str_new(ptr, len);
1786 rb_obj_freeze(str);
1787 return str;
1790 static VALUE
1791 env_str_new2(const char *ptr)
1793 if (!ptr) return Qnil;
1794 return env_str_new(ptr, strlen(ptr));
1797 static VALUE
1798 env_delete(VALUE obj, VALUE name)
1800 char *nam, *val;
1802 rb_secure(4);
1803 SafeStringValue(name);
1804 nam = RSTRING_PTR(name);
1805 if (strlen(nam) != RSTRING_LEN(name)) {
1806 rb_raise(rb_eArgError, "bad environment variable name");
1808 val = getenv(nam);
1809 if (val) {
1810 VALUE value = env_str_new2(val);
1812 ruby_setenv(nam, 0);
1813 #ifdef ENV_IGNORECASE
1814 if (STRCASECMP(nam, PATH_ENV) == 0)
1815 #else
1816 if (strcmp(nam, PATH_ENV) == 0)
1817 #endif
1819 path_tainted = 0;
1821 return value;
1823 return Qnil;
1826 static VALUE
1827 env_delete_m(VALUE obj, VALUE name)
1829 VALUE val;
1831 val = env_delete(obj, name);
1832 if (NIL_P(val) && rb_block_given_p()) rb_yield(name);
1833 return val;
1836 static VALUE
1837 rb_f_getenv(VALUE obj, VALUE name)
1839 char *nam, *env;
1841 rb_secure(4);
1842 SafeStringValue(name);
1843 nam = RSTRING_PTR(name);
1844 if (strlen(nam) != RSTRING_LEN(name)) {
1845 rb_raise(rb_eArgError, "bad environment variable name");
1847 env = getenv(nam);
1848 if (env) {
1849 #ifdef ENV_IGNORECASE
1850 if (STRCASECMP(nam, PATH_ENV) == 0 && !rb_env_path_tainted())
1851 #else
1852 if (strcmp(nam, PATH_ENV) == 0 && !rb_env_path_tainted())
1853 #endif
1855 VALUE str = rb_str_new2(env);
1857 rb_obj_freeze(str);
1858 return str;
1860 return env_str_new2(env);
1862 return Qnil;
1865 static VALUE
1866 env_fetch(int argc, VALUE *argv)
1868 VALUE key, if_none;
1869 long block_given;
1870 char *nam, *env;
1872 rb_secure(4);
1873 rb_scan_args(argc, argv, "11", &key, &if_none);
1874 block_given = rb_block_given_p();
1875 if (block_given && argc == 2) {
1876 rb_warn("block supersedes default value argument");
1878 SafeStringValue(key);
1879 nam = RSTRING_PTR(key);
1880 if (strlen(nam) != RSTRING_LEN(key)) {
1881 rb_raise(rb_eArgError, "bad environment variable name");
1883 env = getenv(nam);
1884 if (!env) {
1885 if (block_given) return rb_yield(key);
1886 if (argc == 1) {
1887 rb_raise(rb_eKeyError, "key not found");
1889 return if_none;
1891 #ifdef ENV_IGNORECASE
1892 if (STRCASECMP(nam, PATH_ENV) == 0 && !rb_env_path_tainted())
1893 #else
1894 if (strcmp(nam, PATH_ENV) == 0 && !rb_env_path_tainted())
1895 #endif
1896 return rb_str_new2(env);
1897 return env_str_new2(env);
1900 static void
1901 path_tainted_p(char *path)
1903 path_tainted = rb_path_check(path)?0:1;
1907 rb_env_path_tainted(void)
1909 if (path_tainted < 0) {
1910 path_tainted_p(getenv(PATH_ENV));
1912 return path_tainted;
1915 #if !defined(_WIN32) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
1916 static int
1917 envix(const char *nam)
1919 register int i, len = strlen(nam);
1920 char **env;
1922 env = GET_ENVIRON(environ);
1923 for (i = 0; env[i]; i++) {
1924 if (
1925 #ifdef ENV_IGNORECASE
1926 STRNCASECMP(env[i],nam,len) == 0
1927 #else
1928 memcmp(env[i],nam,len) == 0
1929 #endif
1930 && env[i][len] == '=')
1931 break; /* memcmp must come first to avoid */
1932 } /* potential SEGV's */
1933 FREE_ENVIRON(environ);
1934 return i;
1936 #endif
1938 void
1939 ruby_setenv(const char *name, const char *value)
1941 #if defined(_WIN32)
1942 /* The sane way to deal with the environment.
1943 * Has these advantages over putenv() & co.:
1944 * * enables us to store a truly empty value in the
1945 * environment (like in UNIX).
1946 * * we don't have to deal with RTL globals, bugs and leaks.
1947 * * Much faster.
1948 * Why you may want to enable USE_WIN32_RTL_ENV:
1949 * * environ[] and RTL functions will not reflect changes,
1950 * which might be an issue if extensions want to access
1951 * the env. via RTL. This cuts both ways, since RTL will
1952 * not see changes made by extensions that call the Win32
1953 * functions directly, either.
1954 * GSAR 97-06-07
1956 * REMARK: USE_WIN32_RTL_ENV is already obsoleted since we don't use
1957 * RTL's environ global variable directly yet.
1959 SetEnvironmentVariable(name,value);
1960 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
1961 #undef setenv
1962 #undef unsetenv
1963 if (value)
1964 setenv(name,value,1);
1965 else
1966 unsetenv(name);
1967 #else /* WIN32 */
1968 size_t len;
1969 int i=envix(name); /* where does it go? */
1971 if (environ == origenviron) { /* need we copy environment? */
1972 int j;
1973 int max;
1974 char **tmpenv;
1976 for (max = i; environ[max]; max++) ;
1977 tmpenv = ALLOC_N(char*, max+2);
1978 for (j=0; j<max; j++) /* copy environment */
1979 tmpenv[j] = strdup(environ[j]);
1980 tmpenv[max] = 0;
1981 environ = tmpenv; /* tell exec where it is now */
1983 if (environ[i]) {
1984 char **envp = origenviron;
1985 while (*envp && *envp != environ[i]) envp++;
1986 if (!*envp)
1987 xfree(environ[i]);
1988 if (!value) {
1989 while (environ[i]) {
1990 environ[i] = environ[i+1];
1991 i++;
1993 return;
1996 else { /* does not exist yet */
1997 if (!value) return;
1998 REALLOC_N(environ, char*, i+2); /* just expand it a bit */
1999 environ[i+1] = 0; /* make sure it's null terminated */
2001 len = strlen(name) + strlen(value) + 2;
2002 environ[i] = ALLOC_N(char, len);
2003 #ifndef MSDOS
2004 snprintf(environ[i],len,"%s=%s",name,value); /* all that work just for this */
2005 #else
2006 /* MS-DOS requires environment variable names to be in uppercase */
2007 /* [Tom Dinger, 27 August 1990: Well, it doesn't _require_ it, but
2008 * some utilities and applications may break because they only look
2009 * for upper case strings. (Fixed strupr() bug here.)]
2011 strcpy(environ[i],name); strupr(environ[i]);
2012 sprintf(environ[i] + strlen(name),"=%s", value);
2013 #endif /* MSDOS */
2015 #endif /* WIN32 */
2018 void
2019 ruby_unsetenv(const char *name)
2021 ruby_setenv(name, 0);
2024 static VALUE
2025 env_aset(VALUE obj, VALUE nm, VALUE val)
2027 char *name, *value;
2029 if (rb_safe_level() >= 4) {
2030 rb_raise(rb_eSecurityError, "can't change environment variable");
2033 if (NIL_P(val)) {
2034 rb_raise(rb_eTypeError, "cannot assign nil; use Hash#delete instead");
2036 StringValue(nm);
2037 StringValue(val);
2038 name = RSTRING_PTR(nm);
2039 value = RSTRING_PTR(val);
2040 if (strlen(name) != RSTRING_LEN(nm))
2041 rb_raise(rb_eArgError, "bad environment variable name");
2042 if (strlen(value) != RSTRING_LEN(val))
2043 rb_raise(rb_eArgError, "bad environment variable value");
2045 ruby_setenv(name, value);
2046 #ifdef ENV_IGNORECASE
2047 if (STRCASECMP(name, PATH_ENV) == 0) {
2048 #else
2049 if (strcmp(name, PATH_ENV) == 0) {
2050 #endif
2051 if (OBJ_TAINTED(val)) {
2052 /* already tainted, no check */
2053 path_tainted = 1;
2054 return val;
2056 else {
2057 path_tainted_p(value);
2060 return val;
2063 static VALUE
2064 env_keys(void)
2066 char **env;
2067 VALUE ary;
2069 rb_secure(4);
2070 ary = rb_ary_new();
2071 env = GET_ENVIRON(environ);
2072 while (*env) {
2073 char *s = strchr(*env, '=');
2074 if (s) {
2075 rb_ary_push(ary, env_str_new(*env, s-*env));
2077 env++;
2079 FREE_ENVIRON(environ);
2080 return ary;
2083 static VALUE
2084 env_each_key(VALUE ehash)
2086 VALUE keys;
2087 long i;
2089 RETURN_ENUMERATOR(ehash, 0, 0);
2090 keys = env_keys(); /* rb_secure(4); */
2091 for (i=0; i<RARRAY_LEN(keys); i++) {
2092 rb_yield(RARRAY_PTR(keys)[i]);
2094 return ehash;
2097 static VALUE
2098 env_values(void)
2100 VALUE ary;
2101 char **env;
2103 rb_secure(4);
2104 ary = rb_ary_new();
2105 env = GET_ENVIRON(environ);
2106 while (*env) {
2107 char *s = strchr(*env, '=');
2108 if (s) {
2109 rb_ary_push(ary, env_str_new2(s+1));
2111 env++;
2113 FREE_ENVIRON(environ);
2114 return ary;
2117 static VALUE
2118 env_each_value(VALUE ehash)
2120 VALUE values;
2121 long i;
2123 RETURN_ENUMERATOR(ehash, 0, 0);
2124 values = env_values(); /* rb_secure(4); */
2125 for (i=0; i<RARRAY_LEN(values); i++) {
2126 rb_yield(RARRAY_PTR(values)[i]);
2128 return ehash;
2131 static VALUE
2132 env_each_pair(VALUE ehash)
2134 char **env;
2135 VALUE ary;
2136 long i;
2138 RETURN_ENUMERATOR(ehash, 0, 0);
2140 rb_secure(4);
2141 ary = rb_ary_new();
2142 env = GET_ENVIRON(environ);
2143 while (*env) {
2144 char *s = strchr(*env, '=');
2145 if (s) {
2146 rb_ary_push(ary, env_str_new(*env, s-*env));
2147 rb_ary_push(ary, env_str_new2(s+1));
2149 env++;
2151 FREE_ENVIRON(environ);
2153 for (i=0; i<RARRAY_LEN(ary); i+=2) {
2154 rb_yield(rb_assoc_new(RARRAY_PTR(ary)[i], RARRAY_PTR(ary)[i+1]));
2156 return ehash;
2159 static VALUE
2160 env_reject_bang(VALUE ehash)
2162 volatile VALUE keys;
2163 long i;
2164 int del = 0;
2166 RETURN_ENUMERATOR(ehash, 0, 0);
2167 keys = env_keys(); /* rb_secure(4); */
2168 for (i=0; i<RARRAY_LEN(keys); i++) {
2169 VALUE val = rb_f_getenv(Qnil, RARRAY_PTR(keys)[i]);
2170 if (!NIL_P(val)) {
2171 if (RTEST(rb_yield_values(2, RARRAY_PTR(keys)[i], val))) {
2172 FL_UNSET(RARRAY_PTR(keys)[i], FL_TAINT);
2173 env_delete(Qnil, RARRAY_PTR(keys)[i]);
2174 del++;
2178 if (del == 0) return Qnil;
2179 return envtbl;
2182 static VALUE
2183 env_delete_if(VALUE ehash)
2185 RETURN_ENUMERATOR(ehash, 0, 0);
2186 env_reject_bang(ehash);
2187 return envtbl;
2190 static VALUE
2191 env_values_at(int argc, VALUE *argv)
2193 VALUE result;
2194 long i;
2196 rb_secure(4);
2197 result = rb_ary_new();
2198 for (i=0; i<argc; i++) {
2199 rb_ary_push(result, rb_f_getenv(Qnil, argv[i]));
2201 return result;
2204 static VALUE
2205 env_select(VALUE ehash)
2207 VALUE result;
2208 char **env;
2210 RETURN_ENUMERATOR(ehash, 0, 0);
2211 rb_secure(4);
2212 result = rb_hash_new();
2213 env = GET_ENVIRON(environ);
2214 while (*env) {
2215 char *s = strchr(*env, '=');
2216 if (s) {
2217 VALUE k = env_str_new(*env, s-*env);
2218 VALUE v = env_str_new2(s+1);
2219 if (RTEST(rb_yield_values(2, k, v))) {
2220 rb_hash_aset(result, k, v);
2223 env++;
2225 FREE_ENVIRON(environ);
2227 return result;
2230 VALUE
2231 rb_env_clear(void)
2233 volatile VALUE keys;
2234 long i;
2236 keys = env_keys(); /* rb_secure(4); */
2237 for (i=0; i<RARRAY_LEN(keys); i++) {
2238 VALUE val = rb_f_getenv(Qnil, RARRAY_PTR(keys)[i]);
2239 if (!NIL_P(val)) {
2240 env_delete(Qnil, RARRAY_PTR(keys)[i]);
2243 return envtbl;
2246 static VALUE
2247 env_to_s(void)
2249 return rb_usascii_str_new2("ENV");
2252 static VALUE
2253 env_inspect(void)
2255 char **env;
2256 VALUE str, i;
2258 rb_secure(4);
2259 str = rb_str_buf_new2("{");
2260 env = GET_ENVIRON(environ);
2261 while (*env) {
2262 char *s = strchr(*env, '=');
2264 if (env != environ) {
2265 rb_str_buf_cat2(str, ", ");
2267 if (s) {
2268 rb_str_buf_cat2(str, "\"");
2269 rb_str_buf_cat(str, *env, s-*env);
2270 rb_str_buf_cat2(str, "\"=>");
2271 i = rb_inspect(rb_str_new2(s+1));
2272 rb_str_buf_append(str, i);
2274 env++;
2276 FREE_ENVIRON(environ);
2277 rb_str_buf_cat2(str, "}");
2278 OBJ_TAINT(str);
2280 return str;
2283 static VALUE
2284 env_to_a(void)
2286 char **env;
2287 VALUE ary;
2289 rb_secure(4);
2290 ary = rb_ary_new();
2291 env = GET_ENVIRON(environ);
2292 while (*env) {
2293 char *s = strchr(*env, '=');
2294 if (s) {
2295 rb_ary_push(ary, rb_assoc_new(env_str_new(*env, s-*env),
2296 env_str_new2(s+1)));
2298 env++;
2300 FREE_ENVIRON(environ);
2301 return ary;
2304 static VALUE
2305 env_none(void)
2307 return Qnil;
2310 static VALUE
2311 env_size(void)
2313 int i;
2314 char **env;
2316 rb_secure(4);
2317 env = GET_ENVIRON(environ);
2318 for(i=0; env[i]; i++)
2320 FREE_ENVIRON(environ);
2321 return INT2FIX(i);
2324 static VALUE
2325 env_empty_p(void)
2327 char **env;
2329 rb_secure(4);
2330 env = GET_ENVIRON(environ);
2331 if (env[0] == 0) {
2332 FREE_ENVIRON(environ);
2333 return Qtrue;
2335 FREE_ENVIRON(environ);
2336 return Qfalse;
2339 static VALUE
2340 env_has_key(VALUE env, VALUE key)
2342 char *s;
2344 rb_secure(4);
2345 s = StringValuePtr(key);
2346 if (strlen(s) != RSTRING_LEN(key))
2347 rb_raise(rb_eArgError, "bad environment variable name");
2348 if (getenv(s)) return Qtrue;
2349 return Qfalse;
2352 static VALUE
2353 env_assoc(VALUE env, VALUE key)
2355 char *s, *e;
2357 rb_secure(4);
2358 s = StringValuePtr(key);
2359 if (strlen(s) != RSTRING_LEN(key))
2360 rb_raise(rb_eArgError, "bad environment variable name");
2361 e = getenv(s);
2362 if (e) return rb_assoc_new(key, rb_tainted_str_new2(e));
2363 return Qnil;
2366 static VALUE
2367 env_has_value(VALUE dmy, VALUE obj)
2369 char **env;
2371 rb_secure(4);
2372 obj = rb_check_string_type(obj);
2373 if (NIL_P(obj)) return Qnil;
2374 env = GET_ENVIRON(environ);
2375 while (*env) {
2376 char *s = strchr(*env, '=');
2377 if (s++) {
2378 long len = strlen(s);
2379 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
2380 FREE_ENVIRON(environ);
2381 return Qtrue;
2384 env++;
2386 FREE_ENVIRON(environ);
2387 return Qfalse;
2390 static VALUE
2391 env_rassoc(VALUE dmy, VALUE obj)
2393 char **env;
2395 rb_secure(4);
2396 obj = rb_check_string_type(obj);
2397 if (NIL_P(obj)) return Qnil;
2398 env = GET_ENVIRON(environ);
2399 while (*env) {
2400 char *s = strchr(*env, '=');
2401 if (s++) {
2402 long len = strlen(s);
2403 if (RSTRING_LEN(obj) == len && strncmp(s, RSTRING_PTR(obj), len) == 0) {
2404 VALUE result = rb_assoc_new(rb_tainted_str_new(*env, s-*env-1), obj);
2405 FREE_ENVIRON(environ);
2406 return result;
2409 env++;
2411 FREE_ENVIRON(environ);
2412 return Qnil;
2415 static VALUE
2416 env_key(VALUE dmy, VALUE value)
2418 char **env;
2419 VALUE str;
2421 rb_secure(4);
2422 StringValue(value);
2423 env = GET_ENVIRON(environ);
2424 while (*env) {
2425 char *s = strchr(*env, '=');
2426 if (s++) {
2427 long len = strlen(s);
2428 if (RSTRING_LEN(value) == len && strncmp(s, RSTRING_PTR(value), len) == 0) {
2429 str = env_str_new(*env, s-*env-1);
2430 FREE_ENVIRON(environ);
2431 return str;
2434 env++;
2436 FREE_ENVIRON(environ);
2437 return Qnil;
2440 static VALUE
2441 env_index(VALUE dmy, VALUE value)
2443 rb_warn("ENV.index is deprecated; use ENV.key");
2444 return env_key(dmy, value);
2447 static VALUE
2448 env_to_hash(void)
2450 char **env;
2451 VALUE hash;
2453 rb_secure(4);
2454 hash = rb_hash_new();
2455 env = GET_ENVIRON(environ);
2456 while (*env) {
2457 char *s = strchr(*env, '=');
2458 if (s) {
2459 rb_hash_aset(hash, env_str_new(*env, s-*env),
2460 env_str_new2(s+1));
2462 env++;
2464 FREE_ENVIRON(environ);
2465 return hash;
2468 static VALUE
2469 env_reject(void)
2471 return rb_hash_delete_if(env_to_hash());
2474 static VALUE
2475 env_shift(void)
2477 char **env;
2479 rb_secure(4);
2480 env = GET_ENVIRON(environ);
2481 if (*env) {
2482 char *s = strchr(*env, '=');
2483 if (s) {
2484 VALUE key = env_str_new(*env, s-*env);
2485 VALUE val = env_str_new2(getenv(RSTRING_PTR(key)));
2486 env_delete(Qnil, key);
2487 return rb_assoc_new(key, val);
2490 FREE_ENVIRON(environ);
2491 return Qnil;
2494 static VALUE
2495 env_invert(void)
2497 return rb_hash_invert(env_to_hash());
2500 static int
2501 env_replace_i(VALUE key, VALUE val, VALUE keys)
2503 if (key != Qundef) {
2504 env_aset(Qnil, key, val);
2505 if (rb_ary_includes(keys, key)) {
2506 rb_ary_delete(keys, key);
2509 return ST_CONTINUE;
2512 static VALUE
2513 env_replace(VALUE env, VALUE hash)
2515 volatile VALUE keys;
2516 long i;
2518 keys = env_keys(); /* rb_secure(4); */
2519 if (env == hash) return env;
2520 hash = to_hash(hash);
2521 rb_hash_foreach(hash, env_replace_i, keys);
2523 for (i=0; i<RARRAY_LEN(keys); i++) {
2524 env_delete(env, RARRAY_PTR(keys)[i]);
2526 return env;
2529 static int
2530 env_update_i(VALUE key, VALUE val)
2532 if (key != Qundef) {
2533 if (rb_block_given_p()) {
2534 val = rb_yield_values(3, key, rb_f_getenv(Qnil, key), val);
2536 env_aset(Qnil, key, val);
2538 return ST_CONTINUE;
2541 static VALUE
2542 env_update(VALUE env, VALUE hash)
2544 rb_secure(4);
2545 if (env == hash) return env;
2546 hash = to_hash(hash);
2547 rb_hash_foreach(hash, env_update_i, 0);
2548 return env;
2552 * A <code>Hash</code> is a collection of key-value pairs. It is
2553 * similar to an <code>Array</code>, except that indexing is done via
2554 * arbitrary keys of any object type, not an integer index. The order
2555 * in which you traverse a hash by either key or value may seem
2556 * arbitrary, and will generally not be in the insertion order.
2558 * Hashes have a <em>default value</em> that is returned when accessing
2559 * keys that do not exist in the hash. By default, that value is
2560 * <code>nil</code>.
2564 void
2565 Init_Hash(void)
2567 #undef rb_intern
2569 id_hash = rb_intern("hash");
2570 id_yield = rb_intern("yield");
2571 id_default = rb_intern("default");
2573 rb_cHash = rb_define_class("Hash", rb_cObject);
2575 rb_include_module(rb_cHash, rb_mEnumerable);
2577 rb_define_alloc_func(rb_cHash, hash_alloc);
2578 rb_define_singleton_method(rb_cHash, "[]", rb_hash_s_create, -1);
2579 rb_define_singleton_method(rb_cHash, "try_convert", rb_hash_s_try_convert, 1);
2580 rb_define_method(rb_cHash,"initialize", rb_hash_initialize, -1);
2581 rb_define_method(rb_cHash,"initialize_copy", rb_hash_replace, 1);
2582 rb_define_method(rb_cHash,"rehash", rb_hash_rehash, 0);
2584 rb_define_method(rb_cHash,"to_hash", rb_hash_to_hash, 0);
2585 rb_define_method(rb_cHash,"to_a", rb_hash_to_a, 0);
2586 rb_define_method(rb_cHash,"to_s", rb_hash_inspect, 0);
2587 rb_define_method(rb_cHash,"inspect", rb_hash_inspect, 0);
2589 rb_define_method(rb_cHash,"==", rb_hash_equal, 1);
2590 rb_define_method(rb_cHash,"[]", rb_hash_aref, 1);
2591 rb_define_method(rb_cHash,"hash", rb_hash_hash, 0);
2592 rb_define_method(rb_cHash,"eql?", rb_hash_eql, 1);
2593 rb_define_method(rb_cHash,"fetch", rb_hash_fetch, -1);
2594 rb_define_method(rb_cHash,"[]=", rb_hash_aset, 2);
2595 rb_define_method(rb_cHash,"store", rb_hash_aset, 2);
2596 rb_define_method(rb_cHash,"default", rb_hash_default, -1);
2597 rb_define_method(rb_cHash,"default=", rb_hash_set_default, 1);
2598 rb_define_method(rb_cHash,"default_proc", rb_hash_default_proc, 0);
2599 rb_define_method(rb_cHash,"key", rb_hash_key, 1);
2600 rb_define_method(rb_cHash,"index", rb_hash_index, 1);
2601 rb_define_method(rb_cHash,"size", rb_hash_size, 0);
2602 rb_define_method(rb_cHash,"length", rb_hash_size, 0);
2603 rb_define_method(rb_cHash,"empty?", rb_hash_empty_p, 0);
2605 rb_define_method(rb_cHash,"each_value", rb_hash_each_value, 0);
2606 rb_define_method(rb_cHash,"each_key", rb_hash_each_key, 0);
2607 rb_define_method(rb_cHash,"each_pair", rb_hash_each_pair, 0);
2608 rb_define_method(rb_cHash,"each", rb_hash_each_pair, 0);
2610 rb_define_method(rb_cHash,"keys", rb_hash_keys, 0);
2611 rb_define_method(rb_cHash,"values", rb_hash_values, 0);
2612 rb_define_method(rb_cHash,"values_at", rb_hash_values_at, -1);
2614 rb_define_method(rb_cHash,"shift", rb_hash_shift, 0);
2615 rb_define_method(rb_cHash,"delete", rb_hash_delete, 1);
2616 rb_define_method(rb_cHash,"delete_if", rb_hash_delete_if, 0);
2617 rb_define_method(rb_cHash,"select", rb_hash_select, 0);
2618 rb_define_method(rb_cHash,"reject", rb_hash_reject, 0);
2619 rb_define_method(rb_cHash,"reject!", rb_hash_reject_bang, 0);
2620 rb_define_method(rb_cHash,"clear", rb_hash_clear, 0);
2621 rb_define_method(rb_cHash,"invert", rb_hash_invert, 0);
2622 rb_define_method(rb_cHash,"update", rb_hash_update, 1);
2623 rb_define_method(rb_cHash,"replace", rb_hash_replace, 1);
2624 rb_define_method(rb_cHash,"merge!", rb_hash_update, 1);
2625 rb_define_method(rb_cHash,"merge", rb_hash_merge, 1);
2626 rb_define_method(rb_cHash, "assoc", rb_hash_assoc, 1);
2627 rb_define_method(rb_cHash, "rassoc", rb_hash_rassoc, 1);
2628 rb_define_method(rb_cHash, "flatten", rb_hash_flatten, -1);
2630 rb_define_method(rb_cHash,"include?", rb_hash_has_key, 1);
2631 rb_define_method(rb_cHash,"member?", rb_hash_has_key, 1);
2632 rb_define_method(rb_cHash,"has_key?", rb_hash_has_key, 1);
2633 rb_define_method(rb_cHash,"has_value?", rb_hash_has_value, 1);
2634 rb_define_method(rb_cHash,"key?", rb_hash_has_key, 1);
2635 rb_define_method(rb_cHash,"value?", rb_hash_has_value, 1);
2637 rb_define_method(rb_cHash,"compare_by_identity", rb_hash_compare_by_id, 0);
2638 rb_define_method(rb_cHash,"compare_by_identity?", rb_hash_compare_by_id_p, 0);
2640 #ifndef __MACOS__ /* environment variables nothing on MacOS. */
2641 origenviron = environ;
2642 envtbl = rb_obj_alloc(rb_cObject);
2643 rb_extend_object(envtbl, rb_mEnumerable);
2645 rb_define_singleton_method(envtbl,"[]", rb_f_getenv, 1);
2646 rb_define_singleton_method(envtbl,"fetch", env_fetch, -1);
2647 rb_define_singleton_method(envtbl,"[]=", env_aset, 2);
2648 rb_define_singleton_method(envtbl,"store", env_aset, 2);
2649 rb_define_singleton_method(envtbl,"each", env_each_pair, 0);
2650 rb_define_singleton_method(envtbl,"each_pair", env_each_pair, 0);
2651 rb_define_singleton_method(envtbl,"each_key", env_each_key, 0);
2652 rb_define_singleton_method(envtbl,"each_value", env_each_value, 0);
2653 rb_define_singleton_method(envtbl,"delete", env_delete_m, 1);
2654 rb_define_singleton_method(envtbl,"delete_if", env_delete_if, 0);
2655 rb_define_singleton_method(envtbl,"clear", rb_env_clear, 0);
2656 rb_define_singleton_method(envtbl,"reject", env_reject, 0);
2657 rb_define_singleton_method(envtbl,"reject!", env_reject_bang, 0);
2658 rb_define_singleton_method(envtbl,"select", env_select, 0);
2659 rb_define_singleton_method(envtbl,"shift", env_shift, 0);
2660 rb_define_singleton_method(envtbl,"invert", env_invert, 0);
2661 rb_define_singleton_method(envtbl,"replace", env_replace, 1);
2662 rb_define_singleton_method(envtbl,"update", env_update, 1);
2663 rb_define_singleton_method(envtbl,"inspect", env_inspect, 0);
2664 rb_define_singleton_method(envtbl,"rehash", env_none, 0);
2665 rb_define_singleton_method(envtbl,"to_a", env_to_a, 0);
2666 rb_define_singleton_method(envtbl,"to_s", env_to_s, 0);
2667 rb_define_singleton_method(envtbl,"key", env_key, 1);
2668 rb_define_singleton_method(envtbl,"index", env_index, 1);
2669 rb_define_singleton_method(envtbl,"size", env_size, 0);
2670 rb_define_singleton_method(envtbl,"length", env_size, 0);
2671 rb_define_singleton_method(envtbl,"empty?", env_empty_p, 0);
2672 rb_define_singleton_method(envtbl,"keys", env_keys, 0);
2673 rb_define_singleton_method(envtbl,"values", env_values, 0);
2674 rb_define_singleton_method(envtbl,"values_at", env_values_at, -1);
2675 rb_define_singleton_method(envtbl,"include?", env_has_key, 1);
2676 rb_define_singleton_method(envtbl,"member?", env_has_key, 1);
2677 rb_define_singleton_method(envtbl,"has_key?", env_has_key, 1);
2678 rb_define_singleton_method(envtbl,"has_value?", env_has_value, 1);
2679 rb_define_singleton_method(envtbl,"key?", env_has_key, 1);
2680 rb_define_singleton_method(envtbl,"value?", env_has_value, 1);
2681 rb_define_singleton_method(envtbl,"to_hash", env_to_hash, 0);
2682 rb_define_singleton_method(envtbl,"assoc", env_assoc, 1);
2683 rb_define_singleton_method(envtbl,"rassoc", env_rassoc, 1);
2685 rb_define_global_const("ENV", envtbl);
2686 #else /* __MACOS__ */
2687 envtbl = rb_hash_s_new(0, NULL, rb_cHash);
2688 rb_define_global_const("ENV", envtbl);
2689 #endif /* ifndef __MACOS__ environment variables nothing on MacOS. */