1 /**********************************************************************
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/internal/config.h"
19 # ifdef HAVE_CRT_EXTERNS_H
20 # include <crt_externs.h>
22 # include "missing/crt_externs.h"
26 #include "debug_counter.h"
29 #include "internal/array.h"
30 #include "internal/bignum.h"
31 #include "internal/basic_operators.h"
32 #include "internal/class.h"
33 #include "internal/cont.h"
34 #include "internal/error.h"
35 #include "internal/hash.h"
36 #include "internal/object.h"
37 #include "internal/proc.h"
38 #include "internal/st.h"
39 #include "internal/symbol.h"
40 #include "internal/thread.h"
41 #include "internal/time.h"
42 #include "internal/vm.h"
45 #include "ruby/util.h"
46 #include "ruby_assert.h"
48 #include "ruby/thread_native.h"
49 #include "ruby/ractor.h"
54 * 1: RHASH_PASS_AS_KEYWORDS
55 * The hash is flagged as Ruby 2 keywords hash.
56 * 2: RHASH_PROC_DEFAULT
57 * The hash has a default proc (rather than a default value).
58 * 3: RHASH_ST_TABLE_FLAG
59 * The hash uses a ST table (rather than an AR table).
60 * 4-7: RHASH_AR_TABLE_SIZE_MASK
61 * The size of the AR table.
62 * 8-11: RHASH_AR_TABLE_BOUND_MASK
63 * The bounds of the AR table.
64 * 13-19: RHASH_LEV_MASK
65 * The iterational level of the hash. Used to prevent modifications
66 * to the hash during interation.
74 #include "internal/gc.h"
77 #define SET_DEFAULT(hash, ifnone) ( \
78 FL_UNSET_RAW(hash, RHASH_PROC_DEFAULT), \
79 RHASH_SET_IFNONE(hash, ifnone))
81 #define SET_PROC_DEFAULT(hash, proc) set_proc_default(hash, proc)
83 #define COPY_DEFAULT(hash, hash2) copy_default(RHASH(hash), RHASH(hash2))
86 copy_default(struct RHash
*hash
, const struct RHash
*hash2
)
88 hash
->basic
.flags
&= ~RHASH_PROC_DEFAULT
;
89 hash
->basic
.flags
|= hash2
->basic
.flags
& RHASH_PROC_DEFAULT
;
90 RHASH_SET_IFNONE(hash
, RHASH_IFNONE((VALUE
)hash2
));
93 static VALUE
rb_hash_s_try_convert(VALUE
, VALUE
);
97 * 1. Check mutate st_* functions
106 rb_hash_freeze(VALUE hash
)
108 return rb_obj_freeze(hash
);
114 static ID id_hash
, id_flatten_bang
;
115 static ID id_hash_iter_lev
;
117 #define id_default idDefault
120 rb_hash_set_ifnone(VALUE hash
, VALUE ifnone
)
122 RB_OBJ_WRITE(hash
, (&RHASH(hash
)->ifnone
), ifnone
);
127 rb_any_cmp(VALUE a
, VALUE b
)
129 if (a
== b
) return 0;
130 if (RB_TYPE_P(a
, T_STRING
) && RBASIC(a
)->klass
== rb_cString
&&
131 RB_TYPE_P(b
, T_STRING
) && RBASIC(b
)->klass
== rb_cString
) {
132 return rb_str_hash_cmp(a
, b
);
134 if (UNDEF_P(a
) || UNDEF_P(b
)) return -1;
135 if (SYMBOL_P(a
) && SYMBOL_P(b
)) {
139 return !rb_eql(a
, b
);
143 hash_recursive(VALUE obj
, VALUE arg
, int recurse
)
145 if (recurse
) return INT2FIX(0);
146 return rb_funcallv(obj
, id_hash
, 0, 0);
149 static long rb_objid_hash(st_index_t index
);
152 dbl_to_index(double d
)
154 union {double d
; st_index_t i
;} u
;
160 rb_dbl_long_hash(double d
)
162 /* normalize -0.0 to 0.0 */
163 if (d
== 0.0) d
= 0.0;
164 #if SIZEOF_INT == SIZEOF_VOIDP
165 return rb_memhash(&d
, sizeof(d
));
167 return rb_objid_hash(dbl_to_index(d
));
172 any_hash(VALUE a
, st_index_t (*other_func
)(VALUE
))
179 if (STATIC_SYM_P(a
)) {
180 hnum
= a
>> (RUBY_SPECIAL_SHIFT
+ ID_SCOPE_SHIFT
);
181 hnum
= rb_hash_start(hnum
);
184 hnum
= RSYMBOL(a
)->hashval
;
191 hnum
= rb_objid_hash((st_index_t
)a
);
194 hnum
= rb_str_hash(a
);
197 hval
= rb_big_hash(a
);
198 hnum
= FIX2LONG(hval
);
200 case T_FLOAT
: /* prevent pathological behavior: [Bug #10761] */
201 hnum
= rb_dbl_long_hash(rb_float_value(a
));
204 hnum
= other_func(a
);
206 if ((SIGNED_VALUE
)hnum
> 0)
213 VALUE
rb_obj_hash(VALUE obj
);
214 VALUE
rb_vm_call0(rb_execution_context_t
*ec
, VALUE recv
, ID id
, int argc
, const VALUE
*argv
, const rb_callable_method_entry_t
*cme
, int kw_splat
);
217 obj_any_hash(VALUE obj
)
220 VALUE klass
= CLASS_OF(obj
);
222 const rb_callable_method_entry_t
*cme
= rb_callable_method_entry(klass
, id_hash
);
223 if (cme
&& METHOD_ENTRY_BASIC(cme
)) {
224 // Optimize away the frame push overhead if it's the default Kernel#hash
225 if (cme
->def
->type
== VM_METHOD_TYPE_CFUNC
&& cme
->def
->body
.cfunc
.func
== (rb_cfunc_t
)rb_obj_hash
) {
226 hval
= rb_obj_hash(obj
);
228 else if (RBASIC_CLASS(cme
->defined_class
) == rb_mKernel
) {
229 hval
= rb_vm_call0(GET_EC(), obj
, id_hash
, 0, 0, cme
, 0);
235 hval
= rb_exec_recursive_outer_mid(hash_recursive
, obj
, 0, id_hash
);
238 while (!FIXNUM_P(hval
)) {
239 if (RB_TYPE_P(hval
, T_BIGNUM
)) {
242 sign
= rb_integer_pack(hval
, &ul
, 1, sizeof(ul
), 0,
243 INTEGER_PACK_NATIVE_BYTE_ORDER
);
245 hval
= LONG2FIX(ul
| FIXNUM_MIN
);
248 hval
= LONG2FIX(ul
& FIXNUM_MAX
);
251 hval
= rb_to_int(hval
);
254 return FIX2LONG(hval
);
260 return any_hash(a
, obj_any_hash
);
266 return LONG2FIX(any_hash(obj
, obj_any_hash
));
270 /* Here is a hash function for 64-bit key. It is about 5 times faster
271 (2 times faster when uint128 type is absent) on Haswell than
272 tailored Spooky or City hash function can be. */
274 /* Here we two primes with random bit generation. */
275 static const uint64_t prime1
= ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
276 static const uint32_t prime2
= 0x830fcab9;
279 static inline uint64_t
280 mult_and_mix(uint64_t m1
, uint64_t m2
)
282 #if defined HAVE_UINT128_T
283 uint128_t r
= (uint128_t
) m1
* (uint128_t
) m2
;
284 return (uint64_t) (r
>> 64) ^ (uint64_t) r
;
286 uint64_t hm1
= m1
>> 32, hm2
= m2
>> 32;
287 uint64_t lm1
= m1
, lm2
= m2
;
288 uint64_t v64_128
= hm1
* hm2
;
289 uint64_t v32_96
= hm1
* lm2
+ lm1
* hm2
;
290 uint64_t v1_32
= lm1
* lm2
;
292 return (v64_128
+ (v32_96
>> 32)) ^ ((v32_96
<< 32) + v1_32
);
296 static inline uint64_t
297 key64_hash(uint64_t key
, uint32_t seed
)
299 return mult_and_mix(key
+ seed
, prime1
);
302 /* Should cast down the result for each purpose */
303 #define st_index_hash(index) key64_hash(rb_hash_start(index), prime2)
306 rb_objid_hash(st_index_t index
)
308 return (long)st_index_hash(index
);
312 objid_hash(VALUE obj
)
314 VALUE object_id
= rb_obj_id(obj
);
315 if (!FIXNUM_P(object_id
))
316 object_id
= rb_big_hash(object_id
);
318 #if SIZEOF_LONG == SIZEOF_VOIDP
319 return (st_index_t
)st_index_hash((st_index_t
)NUM2LONG(object_id
));
320 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
321 return (st_index_t
)st_index_hash((st_index_t
)NUM2LL(object_id
));
327 * obj.hash -> integer
329 * Generates an Integer hash value for this object. This function must have the
330 * property that <code>a.eql?(b)</code> implies <code>a.hash == b.hash</code>.
332 * The hash value is used along with #eql? by the Hash class to determine if
333 * two objects reference the same hash key. Any hash value that exceeds the
334 * capacity of an Integer will be truncated before being used.
336 * The hash value for an object may not be identical across invocations or
337 * implementations of Ruby. If you need a stable identifier across Ruby
338 * invocations and implementations you will need to generate one with a custom
341 * Certain core classes such as Integer use built-in hash calculations and
342 * do not call the #hash method when used as a hash key.
344 * When implementing your own #hash based on multiple values, the best
345 * practice is to combine the class and any values using the hash code of an
351 * [self.class, a, b, c].hash
354 * The reason for this is that the Array#hash method already has logic for
355 * safely and efficiently combining multiple hash values.
361 rb_obj_hash(VALUE obj
)
363 long hnum
= any_hash(obj
, objid_hash
);
367 static const struct st_hash_type objhash
= {
372 #define rb_ident_cmp st_numcmp
375 rb_ident_hash(st_data_t n
)
377 #ifdef USE_FLONUM /* RUBY */
379 * - flonum (on 64-bit) is pathologically bad, mix the actual
380 * float value in, but do not use the float value as-is since
381 * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
384 n
^= dbl_to_index(rb_float_value(n
));
388 return (st_index_t
)st_index_hash((st_index_t
)n
);
391 #define identhash rb_hashtype_ident
392 const struct st_hash_type rb_hashtype_ident
= {
397 #define RHASH_IDENTHASH_P(hash) (RHASH_TYPE(hash) == &identhash)
398 #define RHASH_STRING_KEY_P(hash, key) (!RHASH_IDENTHASH_P(hash) && (rb_obj_class(key) == rb_cString))
400 typedef st_index_t st_hash_t
;
403 * RHASH_AR_TABLE_P(h):
404 * RHASH_AR_TABLE points to ar_table.
406 * !RHASH_AR_TABLE_P(h):
407 * RHASH_ST_TABLE points st_table.
410 #define RHASH_AR_TABLE_MAX_BOUND RHASH_AR_TABLE_MAX_SIZE
412 #define RHASH_AR_TABLE_REF(hash, n) (&RHASH_AR_TABLE(hash)->pairs[n])
413 #define RHASH_AR_CLEARED_HINT 0xff
415 static inline st_hash_t
416 ar_do_hash(st_data_t key
)
418 return (st_hash_t
)rb_any_hash(key
);
421 static inline ar_hint_t
422 ar_do_hash_hint(st_hash_t hash_value
)
424 return (ar_hint_t
)hash_value
;
427 static inline ar_hint_t
428 ar_hint(VALUE hash
, unsigned int index
)
430 return RHASH_AR_TABLE(hash
)->ar_hint
.ary
[index
];
434 ar_hint_set_hint(VALUE hash
, unsigned int index
, ar_hint_t hint
)
436 RHASH_AR_TABLE(hash
)->ar_hint
.ary
[index
] = hint
;
440 ar_hint_set(VALUE hash
, unsigned int index
, st_hash_t hash_value
)
442 ar_hint_set_hint(hash
, index
, ar_do_hash_hint(hash_value
));
446 ar_clear_entry(VALUE hash
, unsigned int index
)
448 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
450 ar_hint_set_hint(hash
, index
, RHASH_AR_CLEARED_HINT
);
454 ar_cleared_entry(VALUE hash
, unsigned int index
)
456 if (ar_hint(hash
, index
) == RHASH_AR_CLEARED_HINT
) {
457 /* RHASH_AR_CLEARED_HINT is only a hint, not mean cleared entry,
458 * so you need to check key == Qundef
460 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
461 return UNDEF_P(pair
->key
);
469 ar_set_entry(VALUE hash
, unsigned int index
, st_data_t key
, st_data_t val
, st_hash_t hash_value
)
471 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
474 ar_hint_set(hash
, index
, hash_value
);
477 #define RHASH_AR_TABLE_SIZE(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
478 RHASH_AR_TABLE_SIZE_RAW(h))
480 #define RHASH_AR_TABLE_BOUND_RAW(h) \
481 ((unsigned int)((RBASIC(h)->flags >> RHASH_AR_TABLE_BOUND_SHIFT) & \
482 (RHASH_AR_TABLE_BOUND_MASK >> RHASH_AR_TABLE_BOUND_SHIFT)))
484 #define RHASH_ST_TABLE_SET(h, s) rb_hash_st_table_set(h, s)
485 #define RHASH_TYPE(hash) (RHASH_AR_TABLE_P(hash) ? &objhash : RHASH_ST_TABLE(hash)->type)
487 #define HASH_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(HASH_DEBUG, expr, #expr)
489 static inline unsigned int
490 RHASH_AR_TABLE_BOUND(VALUE h
)
492 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
493 const unsigned int bound
= RHASH_AR_TABLE_BOUND_RAW(h
);
494 HASH_ASSERT(bound
<= RHASH_AR_TABLE_MAX_SIZE
);
499 #define hash_verify(hash) hash_verify_(hash, __FILE__, __LINE__)
502 rb_hash_dump(VALUE hash
)
504 rb_obj_info_dump(hash
);
506 if (RHASH_AR_TABLE_P(hash
)) {
507 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
509 fprintf(stderr
, " size:%u bound:%u\n",
510 RHASH_AR_TABLE_SIZE(hash
), bound
);
512 for (i
=0; i
<bound
; i
++) {
515 if (!ar_cleared_entry(hash
, i
)) {
516 char b1
[0x100], b2
[0x100];
517 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
520 fprintf(stderr
, " %d key:%s val:%s hint:%02x\n", i
,
521 rb_raw_obj_info(b1
, 0x100, k
),
522 rb_raw_obj_info(b2
, 0x100, v
),
526 fprintf(stderr
, " %d empty\n", i
);
533 hash_verify_(VALUE hash
, const char *file
, int line
)
535 HASH_ASSERT(RB_TYPE_P(hash
, T_HASH
));
537 if (RHASH_AR_TABLE_P(hash
)) {
538 unsigned i
, n
= 0, bound
= RHASH_AR_TABLE_BOUND(hash
);
540 for (i
=0; i
<bound
; i
++) {
542 if (!ar_cleared_entry(hash
, i
)) {
543 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
546 HASH_ASSERT(!UNDEF_P(k
));
547 HASH_ASSERT(!UNDEF_P(v
));
551 if (n
!= RHASH_AR_TABLE_SIZE(hash
)) {
552 rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n
, RHASH_AR_TABLE_SIZE(hash
));
556 HASH_ASSERT(RHASH_ST_TABLE(hash
) != NULL
);
557 HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash
) == 0);
558 HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash
) == 0);
565 #define hash_verify(h) ((void)0)
569 RHASH_TABLE_EMPTY_P(VALUE hash
)
571 return RHASH_SIZE(hash
) == 0;
574 #define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
575 #define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
578 hash_st_table_init(VALUE hash
, const struct st_hash_type
*type
, st_index_t size
)
580 st_init_existing_table_with_size(RHASH_ST_TABLE(hash
), type
, size
);
581 RHASH_SET_ST_FLAG(hash
);
585 rb_hash_st_table_set(VALUE hash
, st_table
*st
)
587 HASH_ASSERT(st
!= NULL
);
588 RHASH_SET_ST_FLAG(hash
);
590 *RHASH_ST_TABLE(hash
) = *st
;
594 RHASH_AR_TABLE_BOUND_SET(VALUE h
, st_index_t n
)
596 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
597 HASH_ASSERT(n
<= RHASH_AR_TABLE_MAX_BOUND
);
599 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_BOUND_MASK
;
600 RBASIC(h
)->flags
|= n
<< RHASH_AR_TABLE_BOUND_SHIFT
;
604 RHASH_AR_TABLE_SIZE_SET(VALUE h
, st_index_t n
)
606 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
607 HASH_ASSERT(n
<= RHASH_AR_TABLE_MAX_SIZE
);
609 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_SIZE_MASK
;
610 RBASIC(h
)->flags
|= n
<< RHASH_AR_TABLE_SIZE_SHIFT
;
614 HASH_AR_TABLE_SIZE_ADD(VALUE h
, st_index_t n
)
616 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
618 RHASH_AR_TABLE_SIZE_SET(h
, RHASH_AR_TABLE_SIZE(h
) + n
);
623 #define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
626 RHASH_AR_TABLE_SIZE_DEC(VALUE h
)
628 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
629 int new_size
= RHASH_AR_TABLE_SIZE(h
) - 1;
632 RHASH_AR_TABLE_SIZE_SET(h
, new_size
);
635 RHASH_AR_TABLE_SIZE_SET(h
, 0);
636 RHASH_AR_TABLE_BOUND_SET(h
, 0);
642 RHASH_AR_TABLE_CLEAR(VALUE h
)
644 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_SIZE_MASK
;
645 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_BOUND_MASK
;
647 memset(RHASH_AR_TABLE(h
), 0, sizeof(ar_table
));
650 NOINLINE(static int ar_equal(VALUE x
, VALUE y
));
653 ar_equal(VALUE x
, VALUE y
)
655 return rb_any_cmp(x
, y
) == 0;
659 ar_find_entry_hint(VALUE hash
, ar_hint_t hint
, st_data_t key
)
661 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
662 const ar_hint_t
*hints
= RHASH_AR_TABLE(hash
)->ar_hint
.ary
;
664 /* if table is NULL, then bound also should be 0 */
666 for (i
= 0; i
< bound
; i
++) {
667 if (hints
[i
] == hint
) {
668 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
669 if (ar_equal(key
, pair
->key
)) {
670 RB_DEBUG_COUNTER_INC(artable_hint_hit
);
676 static char fname
[256];
679 if (pid
!= getpid()) {
680 snprintf(fname
, sizeof(fname
), "/tmp/ruby-armiss.%d", pid
= getpid());
681 if ((fp
= fopen(fname
, "w")) == NULL
) rb_bug("fopen");
684 st_hash_t h1
= ar_do_hash(key
);
685 st_hash_t h2
= ar_do_hash(pair
->key
);
687 fprintf(fp
, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
689 " pair->key:%016lx %s\n",
690 h1
== h2
, i
, hints
[i
], hint
,
691 h1
, rb_obj_info(key
), h2
, rb_obj_info(pair
->key
));
693 RB_DEBUG_COUNTER_INC(artable_hint_miss
);
697 RB_DEBUG_COUNTER_INC(artable_hint_notfound
);
698 return RHASH_AR_TABLE_MAX_BOUND
;
702 ar_find_entry(VALUE hash
, st_hash_t hash_value
, st_data_t key
)
704 ar_hint_t hint
= ar_do_hash_hint(hash_value
);
705 return ar_find_entry_hint(hash
, hint
, key
);
709 hash_ar_free_and_clear_table(VALUE hash
)
711 RHASH_AR_TABLE_CLEAR(hash
);
713 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash
) == 0);
714 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash
) == 0);
717 void rb_st_add_direct_with_hash(st_table
*tab
, st_data_t key
, st_data_t value
, st_hash_t hash
); // st.c
719 enum ar_each_key_type
{
726 ar_each_key(ar_table
*ar
, int max
, enum ar_each_key_type type
, st_data_t
*dst_keys
, st_table
*new_tab
, st_hash_t
*hashes
)
728 for (int i
= 0; i
< max
; i
++) {
729 ar_table_pair
*pair
= &ar
->pairs
[i
];
732 case ar_each_key_copy
:
733 dst_keys
[i
] = pair
->key
;
735 case ar_each_key_cmp
:
736 if (dst_keys
[i
] != pair
->key
) return 1;
738 case ar_each_key_insert
:
739 if (UNDEF_P(pair
->key
)) continue; // deleted entry
740 rb_st_add_direct_with_hash(new_tab
, pair
->key
, pair
->val
, hashes
[i
]);
749 ar_force_convert_table(VALUE hash
, const char *file
, int line
)
751 if (RHASH_ST_TABLE_P(hash
)) {
752 return RHASH_ST_TABLE(hash
);
755 ar_table
*ar
= RHASH_AR_TABLE(hash
);
756 st_hash_t hashes
[RHASH_AR_TABLE_MAX_SIZE
];
757 unsigned int bound
, size
;
759 // prepare hash values
761 st_data_t keys
[RHASH_AR_TABLE_MAX_SIZE
];
762 bound
= RHASH_AR_TABLE_BOUND(hash
);
763 size
= RHASH_AR_TABLE_SIZE(hash
);
764 ar_each_key(ar
, bound
, ar_each_key_copy
, keys
, NULL
, NULL
);
766 for (unsigned int i
= 0; i
< bound
; i
++) {
767 // do_hash calls #hash method and it can modify hash object
768 hashes
[i
] = UNDEF_P(keys
[i
]) ? 0 : ar_do_hash(keys
[i
]);
772 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) return RHASH_ST_TABLE(hash
);
773 if (UNLIKELY(RHASH_AR_TABLE_BOUND(hash
) != bound
)) continue;
774 if (UNLIKELY(ar_each_key(ar
, bound
, ar_each_key_cmp
, keys
, NULL
, NULL
))) continue;
779 st_table
*new_tab
= &tab
;
780 st_init_existing_table_with_size(new_tab
, &objhash
, size
);
781 ar_each_key(ar
, bound
, ar_each_key_insert
, NULL
, new_tab
, hashes
);
782 hash_ar_free_and_clear_table(hash
);
783 RHASH_ST_TABLE_SET(hash
, new_tab
);
784 return RHASH_ST_TABLE(hash
);
789 ar_compact_table(VALUE hash
)
791 const unsigned bound
= RHASH_AR_TABLE_BOUND(hash
);
792 const unsigned size
= RHASH_AR_TABLE_SIZE(hash
);
799 ar_table_pair
*pairs
= RHASH_AR_TABLE(hash
)->pairs
;
801 for (i
=0; i
<bound
; i
++) {
802 if (ar_cleared_entry(hash
, i
)) {
804 for (; j
<bound
; j
++) {
805 if (!ar_cleared_entry(hash
, j
)) {
807 ar_hint_set_hint(hash
, i
, (st_hash_t
)ar_hint(hash
, j
));
808 ar_clear_entry(hash
, j
);
813 /* non-empty is not found */
819 HASH_ASSERT(i
<=bound
);
821 RHASH_AR_TABLE_BOUND_SET(hash
, size
);
828 ar_add_direct_with_hash(VALUE hash
, st_data_t key
, st_data_t val
, st_hash_t hash_value
)
830 unsigned bin
= RHASH_AR_TABLE_BOUND(hash
);
832 if (RHASH_AR_TABLE_SIZE(hash
) >= RHASH_AR_TABLE_MAX_SIZE
) {
836 if (UNLIKELY(bin
>= RHASH_AR_TABLE_MAX_BOUND
)) {
837 bin
= ar_compact_table(hash
);
839 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
841 ar_set_entry(hash
, bin
, key
, val
, hash_value
);
842 RHASH_AR_TABLE_BOUND_SET(hash
, bin
+1);
843 RHASH_AR_TABLE_SIZE_INC(hash
);
849 ensure_ar_table(VALUE hash
)
851 if (!RHASH_AR_TABLE_P(hash
)) {
852 rb_raise(rb_eRuntimeError
, "hash representation was changed during iteration");
857 ar_general_foreach(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
859 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
860 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
862 for (i
= 0; i
< bound
; i
++) {
863 if (ar_cleared_entry(hash
, i
)) continue;
865 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
866 st_data_t key
= (st_data_t
)pair
->key
;
867 st_data_t val
= (st_data_t
)pair
->val
;
868 enum st_retval retval
= (*func
)(key
, val
, arg
, 0);
869 ensure_ar_table(hash
);
870 /* pair may be not valid here because of theap */
880 retval
= (*replace
)(&key
, &val
, arg
, TRUE
);
882 // TODO: pair should be same as pair before.
883 pair
= RHASH_AR_TABLE_REF(hash
, i
);
884 pair
->key
= (VALUE
)key
;
885 pair
->val
= (VALUE
)val
;
889 ar_clear_entry(hash
, i
);
890 RHASH_AR_TABLE_SIZE_DEC(hash
);
899 ar_foreach_with_replace(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
901 return ar_general_foreach(hash
, func
, replace
, arg
);
905 st_foreach_callback_func
*func
;
910 apply_functor(st_data_t k
, st_data_t v
, st_data_t d
, int _
)
912 const struct functor
*f
= (void *)d
;
913 return f
->func(k
, v
, f
->arg
);
917 ar_foreach(VALUE hash
, st_foreach_callback_func
*func
, st_data_t arg
)
919 const struct functor f
= { func
, arg
};
920 return ar_general_foreach(hash
, apply_functor
, NULL
, (st_data_t
)&f
);
924 ar_foreach_check(VALUE hash
, st_foreach_check_callback_func
*func
, st_data_t arg
,
927 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
928 unsigned i
, ret
= 0, bound
= RHASH_AR_TABLE_BOUND(hash
);
929 enum st_retval retval
;
934 for (i
= 0; i
< bound
; i
++) {
935 if (ar_cleared_entry(hash
, i
)) continue;
937 pair
= RHASH_AR_TABLE_REF(hash
, i
);
939 hint
= ar_hint(hash
, i
);
941 retval
= (*func
)(key
, pair
->val
, arg
, 0);
942 ensure_ar_table(hash
);
947 pair
= RHASH_AR_TABLE_REF(hash
, i
);
948 if (pair
->key
== never
) break;
949 ret
= ar_find_entry_hint(hash
, hint
, key
);
950 if (ret
== RHASH_AR_TABLE_MAX_BOUND
) {
951 retval
= (*func
)(0, 0, arg
, 1);
961 if (!ar_cleared_entry(hash
, i
)) {
962 ar_clear_entry(hash
, i
);
963 RHASH_AR_TABLE_SIZE_DEC(hash
);
974 ar_update(VALUE hash
, st_data_t key
,
975 st_update_callback_func
*func
, st_data_t arg
)
977 int retval
, existing
;
978 unsigned bin
= RHASH_AR_TABLE_MAX_BOUND
;
979 st_data_t value
= 0, old_key
;
980 st_hash_t hash_value
= ar_do_hash(key
);
982 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
983 // `#hash` changes ar_table -> st_table
987 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
988 bin
= ar_find_entry(hash
, hash_value
, key
);
989 existing
= (bin
!= RHASH_AR_TABLE_MAX_BOUND
) ? TRUE
: FALSE
;
996 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1001 retval
= (*func
)(&key
, &value
, arg
, existing
);
1002 /* pair can be invalid here because of theap */
1003 ensure_ar_table(hash
);
1008 if (ar_add_direct_with_hash(hash
, key
, value
, hash_value
)) {
1013 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1014 if (old_key
!= key
) {
1022 ar_clear_entry(hash
, bin
);
1023 RHASH_AR_TABLE_SIZE_DEC(hash
);
1031 ar_insert(VALUE hash
, st_data_t key
, st_data_t value
)
1033 unsigned bin
= RHASH_AR_TABLE_BOUND(hash
);
1034 st_hash_t hash_value
= ar_do_hash(key
);
1036 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1037 // `#hash` changes ar_table -> st_table
1041 bin
= ar_find_entry(hash
, hash_value
, key
);
1042 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1043 if (RHASH_AR_TABLE_SIZE(hash
) >= RHASH_AR_TABLE_MAX_SIZE
) {
1046 else if (bin
>= RHASH_AR_TABLE_MAX_BOUND
) {
1047 bin
= ar_compact_table(hash
);
1049 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
1051 ar_set_entry(hash
, bin
, key
, value
, hash_value
);
1052 RHASH_AR_TABLE_BOUND_SET(hash
, bin
+1);
1053 RHASH_AR_TABLE_SIZE_INC(hash
);
1057 RHASH_AR_TABLE_REF(hash
, bin
)->val
= value
;
1063 ar_lookup(VALUE hash
, st_data_t key
, st_data_t
*value
)
1065 if (RHASH_AR_TABLE_SIZE(hash
) == 0) {
1069 st_hash_t hash_value
= ar_do_hash(key
);
1070 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1071 // `#hash` changes ar_table -> st_table
1072 return st_lookup(RHASH_ST_TABLE(hash
), key
, value
);
1074 unsigned bin
= ar_find_entry(hash
, hash_value
, key
);
1076 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1080 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
1081 if (value
!= NULL
) {
1082 *value
= RHASH_AR_TABLE_REF(hash
, bin
)->val
;
1090 ar_delete(VALUE hash
, st_data_t
*key
, st_data_t
*value
)
1093 st_hash_t hash_value
= ar_do_hash(*key
);
1095 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1096 // `#hash` changes ar_table -> st_table
1097 return st_delete(RHASH_ST_TABLE(hash
), key
, value
);
1100 bin
= ar_find_entry(hash
, hash_value
, *key
);
1102 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1103 if (value
!= 0) *value
= 0;
1108 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1111 ar_clear_entry(hash
, bin
);
1112 RHASH_AR_TABLE_SIZE_DEC(hash
);
1118 ar_shift(VALUE hash
, st_data_t
*key
, st_data_t
*value
)
1120 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
1121 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1123 for (i
= 0; i
< bound
; i
++) {
1124 if (!ar_cleared_entry(hash
, i
)) {
1125 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
1126 if (value
!= 0) *value
= pair
->val
;
1128 ar_clear_entry(hash
, i
);
1129 RHASH_AR_TABLE_SIZE_DEC(hash
);
1134 if (value
!= NULL
) *value
= 0;
1139 ar_keys(VALUE hash
, st_data_t
*keys
, st_index_t size
)
1141 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1142 st_data_t
*keys_start
= keys
, *keys_end
= keys
+ size
;
1144 for (i
= 0; i
< bound
; i
++) {
1145 if (keys
== keys_end
) {
1149 if (!ar_cleared_entry(hash
, i
)) {
1150 *keys
++ = RHASH_AR_TABLE_REF(hash
, i
)->key
;
1155 return keys
- keys_start
;
1159 ar_values(VALUE hash
, st_data_t
*values
, st_index_t size
)
1161 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1162 st_data_t
*values_start
= values
, *values_end
= values
+ size
;
1164 for (i
= 0; i
< bound
; i
++) {
1165 if (values
== values_end
) {
1169 if (!ar_cleared_entry(hash
, i
)) {
1170 *values
++ = RHASH_AR_TABLE_REF(hash
, i
)->val
;
1175 return values
- values_start
;
1179 ar_copy(VALUE hash1
, VALUE hash2
)
1181 ar_table
*old_tab
= RHASH_AR_TABLE(hash2
);
1182 ar_table
*new_tab
= RHASH_AR_TABLE(hash1
);
1184 *new_tab
= *old_tab
;
1185 RHASH_AR_TABLE(hash1
)->ar_hint
.word
= RHASH_AR_TABLE(hash2
)->ar_hint
.word
;
1186 RHASH_AR_TABLE_BOUND_SET(hash1
, RHASH_AR_TABLE_BOUND(hash2
));
1187 RHASH_AR_TABLE_SIZE_SET(hash1
, RHASH_AR_TABLE_SIZE(hash2
));
1189 rb_gc_writebarrier_remember(hash1
);
1195 ar_clear(VALUE hash
)
1197 if (RHASH_AR_TABLE(hash
) != NULL
) {
1198 RHASH_AR_TABLE_SIZE_SET(hash
, 0);
1199 RHASH_AR_TABLE_BOUND_SET(hash
, 0);
1202 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash
) == 0);
1203 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash
) == 0);
1208 hash_st_free(VALUE hash
)
1210 HASH_ASSERT(RHASH_ST_TABLE_P(hash
));
1212 st_table
*tab
= RHASH_ST_TABLE(hash
);
1215 xfree(tab
->entries
);
1219 hash_st_free_and_clear_table(VALUE hash
)
1223 RHASH_ST_CLEAR(hash
);
1227 rb_hash_free(VALUE hash
)
1229 if (RHASH_ST_TABLE_P(hash
)) {
1234 typedef int st_foreach_func(st_data_t
, st_data_t
, st_data_t
);
1236 struct foreach_safe_arg
{
1238 st_foreach_func
*func
;
1243 foreach_safe_i(st_data_t key
, st_data_t value
, st_data_t args
, int error
)
1246 struct foreach_safe_arg
*arg
= (void *)args
;
1248 if (error
) return ST_STOP
;
1249 status
= (*arg
->func
)(key
, value
, arg
->arg
);
1250 if (status
== ST_CONTINUE
) {
1257 st_foreach_safe(st_table
*table
, st_foreach_func
*func
, st_data_t a
)
1259 struct foreach_safe_arg arg
;
1262 arg
.func
= (st_foreach_func
*)func
;
1264 if (st_foreach_check(table
, foreach_safe_i
, (st_data_t
)&arg
, 0)) {
1265 rb_raise(rb_eRuntimeError
, "hash modified during iteration");
1269 typedef int rb_foreach_func(VALUE
, VALUE
, VALUE
);
1271 struct hash_foreach_arg
{
1273 rb_foreach_func
*func
;
1278 hash_iter_status_check(int status
)
1293 hash_ar_foreach_iter(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
1295 struct hash_foreach_arg
*arg
= (struct hash_foreach_arg
*)argp
;
1297 if (error
) return ST_STOP
;
1299 int status
= (*arg
->func
)((VALUE
)key
, (VALUE
)value
, arg
->arg
);
1300 /* TODO: rehash check? rb_raise(rb_eRuntimeError, "rehash occurred during iteration"); */
1302 return hash_iter_status_check(status
);
1306 hash_foreach_iter(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
1308 struct hash_foreach_arg
*arg
= (struct hash_foreach_arg
*)argp
;
1310 if (error
) return ST_STOP
;
1312 st_table
*tbl
= RHASH_ST_TABLE(arg
->hash
);
1313 int status
= (*arg
->func
)((VALUE
)key
, (VALUE
)value
, arg
->arg
);
1315 if (RHASH_ST_TABLE(arg
->hash
) != tbl
) {
1316 rb_raise(rb_eRuntimeError
, "rehash occurred during iteration");
1319 return hash_iter_status_check(status
);
1322 static unsigned long
1323 iter_lev_in_ivar(VALUE hash
)
1325 VALUE levval
= rb_ivar_get(hash
, id_hash_iter_lev
);
1326 HASH_ASSERT(FIXNUM_P(levval
));
1327 long lev
= FIX2LONG(levval
);
1328 HASH_ASSERT(lev
>= 0);
1329 return (unsigned long)lev
;
1332 void rb_ivar_set_internal(VALUE obj
, ID id
, VALUE val
);
1335 iter_lev_in_ivar_set(VALUE hash
, unsigned long lev
)
1337 HASH_ASSERT(lev
>= RHASH_LEV_MAX
);
1338 HASH_ASSERT(POSFIXABLE(lev
)); /* POSFIXABLE means fitting to long */
1339 rb_ivar_set_internal(hash
, id_hash_iter_lev
, LONG2FIX((long)lev
));
1342 static inline unsigned long
1343 iter_lev_in_flags(VALUE hash
)
1345 return (unsigned long)((RBASIC(hash
)->flags
>> RHASH_LEV_SHIFT
) & RHASH_LEV_MAX
);
1349 iter_lev_in_flags_set(VALUE hash
, unsigned long lev
)
1351 HASH_ASSERT(lev
<= RHASH_LEV_MAX
);
1352 RBASIC(hash
)->flags
= ((RBASIC(hash
)->flags
& ~RHASH_LEV_MASK
) | ((VALUE
)lev
<< RHASH_LEV_SHIFT
));
1356 hash_iterating_p(VALUE hash
)
1358 return iter_lev_in_flags(hash
) > 0;
1362 hash_iter_lev_inc(VALUE hash
)
1364 unsigned long lev
= iter_lev_in_flags(hash
);
1365 if (lev
== RHASH_LEV_MAX
) {
1366 lev
= iter_lev_in_ivar(hash
) + 1;
1367 if (!POSFIXABLE(lev
)) { /* paranoiac check */
1368 rb_raise(rb_eRuntimeError
, "too much nested iterations");
1373 iter_lev_in_flags_set(hash
, lev
);
1374 if (lev
< RHASH_LEV_MAX
) return;
1376 iter_lev_in_ivar_set(hash
, lev
);
1380 hash_iter_lev_dec(VALUE hash
)
1382 unsigned long lev
= iter_lev_in_flags(hash
);
1383 if (lev
== RHASH_LEV_MAX
) {
1384 lev
= iter_lev_in_ivar(hash
);
1385 if (lev
> RHASH_LEV_MAX
) {
1386 iter_lev_in_ivar_set(hash
, lev
-1);
1389 rb_attr_delete(hash
, id_hash_iter_lev
);
1391 else if (lev
== 0) {
1392 rb_raise(rb_eRuntimeError
, "iteration level underflow");
1394 iter_lev_in_flags_set(hash
, lev
- 1);
1398 hash_foreach_ensure_rollback(VALUE hash
)
1400 hash_iter_lev_inc(hash
);
1405 hash_foreach_ensure(VALUE hash
)
1407 hash_iter_lev_dec(hash
);
1412 rb_hash_stlike_foreach(VALUE hash
, st_foreach_callback_func
*func
, st_data_t arg
)
1414 if (RHASH_AR_TABLE_P(hash
)) {
1415 return ar_foreach(hash
, func
, arg
);
1418 return st_foreach(RHASH_ST_TABLE(hash
), func
, arg
);
1423 rb_hash_stlike_foreach_with_replace(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
1425 if (RHASH_AR_TABLE_P(hash
)) {
1426 return ar_foreach_with_replace(hash
, func
, replace
, arg
);
1429 return st_foreach_with_replace(RHASH_ST_TABLE(hash
), func
, replace
, arg
);
1434 hash_foreach_call(VALUE arg
)
1436 VALUE hash
= ((struct hash_foreach_arg
*)arg
)->hash
;
1438 if (RHASH_AR_TABLE_P(hash
)) {
1439 ret
= ar_foreach_check(hash
, hash_ar_foreach_iter
,
1440 (st_data_t
)arg
, (st_data_t
)Qundef
);
1442 else if (RHASH_ST_TABLE_P(hash
)) {
1443 ret
= st_foreach_check(RHASH_ST_TABLE(hash
), hash_foreach_iter
,
1444 (st_data_t
)arg
, (st_data_t
)Qundef
);
1447 rb_raise(rb_eRuntimeError
, "ret: %d, hash modified during iteration", ret
);
1453 rb_hash_foreach(VALUE hash
, rb_foreach_func
*func
, VALUE farg
)
1455 struct hash_foreach_arg arg
;
1457 if (RHASH_TABLE_EMPTY_P(hash
))
1460 arg
.func
= (rb_foreach_func
*)func
;
1462 if (RB_OBJ_FROZEN(hash
)) {
1463 hash_foreach_call((VALUE
)&arg
);
1466 hash_iter_lev_inc(hash
);
1467 rb_ensure(hash_foreach_call
, (VALUE
)&arg
, hash_foreach_ensure
, hash
);
1472 void rb_st_compact_table(st_table
*tab
);
1475 compact_after_delete(VALUE hash
)
1477 if (!hash_iterating_p(hash
) && RHASH_ST_TABLE_P(hash
)) {
1478 rb_st_compact_table(RHASH_ST_TABLE(hash
));
1483 hash_alloc_flags(VALUE klass
, VALUE flags
, VALUE ifnone
, bool st
)
1485 const VALUE wb
= (RGENGC_WB_PROTECTED_HASH
? FL_WB_PROTECTED
: 0);
1486 const size_t size
= sizeof(struct RHash
) + (st
? sizeof(st_table
) : sizeof(ar_table
));
1488 NEWOBJ_OF(hash
, struct RHash
, klass
, T_HASH
| wb
| flags
, size
, 0);
1490 RHASH_SET_IFNONE((VALUE
)hash
, ifnone
);
1496 hash_alloc(VALUE klass
)
1498 /* Allocate to be able to fit both st_table and ar_table. */
1499 return hash_alloc_flags(klass
, 0, Qnil
, sizeof(st_table
) > sizeof(ar_table
));
1503 empty_hash_alloc(VALUE klass
)
1505 RUBY_DTRACE_CREATE_HOOK(HASH
, 0);
1507 return hash_alloc(klass
);
1513 return hash_alloc(rb_cHash
);
1517 copy_compare_by_id(VALUE hash
, VALUE basis
)
1519 if (rb_hash_compare_by_id_p(basis
)) {
1520 return rb_hash_compare_by_id(hash
);
1526 rb_hash_new_with_size(st_index_t size
)
1528 bool st
= size
> RHASH_AR_TABLE_MAX_SIZE
;
1529 VALUE ret
= hash_alloc_flags(rb_cHash
, 0, Qnil
, st
);
1532 hash_st_table_init(ret
, &objhash
, size
);
1539 rb_hash_new_capa(long capa
)
1541 return rb_hash_new_with_size((st_index_t
)capa
);
1545 hash_copy(VALUE ret
, VALUE hash
)
1547 if (RHASH_AR_TABLE_P(hash
)) {
1548 if (RHASH_AR_TABLE_P(ret
)) {
1552 st_table
*tab
= RHASH_ST_TABLE(ret
);
1553 st_init_existing_table_with_size(tab
, &objhash
, RHASH_AR_TABLE_SIZE(hash
));
1555 int bound
= RHASH_AR_TABLE_BOUND(hash
);
1556 for (int i
= 0; i
< bound
; i
++) {
1557 if (ar_cleared_entry(hash
, i
)) continue;
1559 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
1560 st_add_direct(tab
, pair
->key
, pair
->val
);
1561 RB_OBJ_WRITTEN(ret
, Qundef
, pair
->key
);
1562 RB_OBJ_WRITTEN(ret
, Qundef
, pair
->val
);
1567 HASH_ASSERT(sizeof(st_table
) <= sizeof(ar_table
));
1569 RHASH_SET_ST_FLAG(ret
);
1570 st_replace(RHASH_ST_TABLE(ret
), RHASH_ST_TABLE(hash
));
1572 rb_gc_writebarrier_remember(ret
);
1578 hash_dup_with_compare_by_id(VALUE hash
)
1580 VALUE dup
= hash_alloc_flags(rb_cHash
, 0, Qnil
, RHASH_ST_TABLE_P(hash
));
1581 if (RHASH_ST_TABLE_P(hash
)) {
1582 RHASH_SET_ST_FLAG(dup
);
1585 RHASH_UNSET_ST_FLAG(dup
);
1588 return hash_copy(dup
, hash
);
1592 hash_dup(VALUE hash
, VALUE klass
, VALUE flags
)
1594 return hash_copy(hash_alloc_flags(klass
, flags
, RHASH_IFNONE(hash
), !RHASH_EMPTY_P(hash
) && RHASH_ST_TABLE_P(hash
)),
1599 rb_hash_dup(VALUE hash
)
1601 const VALUE flags
= RBASIC(hash
)->flags
;
1602 VALUE ret
= hash_dup(hash
, rb_obj_class(hash
),
1603 flags
& (FL_EXIVAR
|RHASH_PROC_DEFAULT
));
1604 if (flags
& FL_EXIVAR
)
1605 rb_copy_generic_ivar(ret
, hash
);
1610 rb_hash_resurrect(VALUE hash
)
1612 VALUE ret
= hash_dup(hash
, rb_cHash
, 0);
1617 rb_hash_modify_check(VALUE hash
)
1619 rb_check_frozen(hash
);
1623 rb_hash_tbl_raw(VALUE hash
, const char *file
, int line
)
1625 return ar_force_convert_table(hash
, file
, line
);
1629 rb_hash_tbl(VALUE hash
, const char *file
, int line
)
1631 OBJ_WB_UNPROTECT(hash
);
1632 return rb_hash_tbl_raw(hash
, file
, line
);
1636 rb_hash_modify(VALUE hash
)
1638 rb_hash_modify_check(hash
);
1641 NORETURN(static void no_new_key(void));
1645 rb_raise(rb_eRuntimeError
, "can't add a new key into hash during iteration");
1648 struct update_callback_arg
{
1653 #define NOINSERT_UPDATE_CALLBACK(func) \
1655 func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1657 if (!existing) no_new_key(); \
1658 return func(key, val, (struct update_arg *)arg, existing); \
1662 func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1664 return func(key, val, (struct update_arg *)arg, existing); \
1669 st_update_callback_func
*func
;
1675 typedef int (*tbl_update_func
)(st_data_t
*, st_data_t
*, st_data_t
, int);
1678 rb_hash_stlike_update(VALUE hash
, st_data_t key
, st_update_callback_func
*func
, st_data_t arg
)
1680 if (RHASH_AR_TABLE_P(hash
)) {
1681 int result
= ar_update(hash
, key
, func
, arg
);
1683 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
1690 return st_update(RHASH_ST_TABLE(hash
), key
, func
, arg
);
1694 tbl_update_modify(st_data_t
*key
, st_data_t
*val
, st_data_t arg
, int existing
)
1696 struct update_arg
*p
= (struct update_arg
*)arg
;
1697 st_data_t old_key
= *key
;
1698 st_data_t old_value
= *val
;
1699 VALUE hash
= p
->hash
;
1700 int ret
= (p
->func
)(key
, val
, arg
, existing
);
1705 if (!existing
|| *key
!= old_key
|| *val
!= old_value
) {
1706 rb_hash_modify(hash
);
1713 rb_hash_modify(hash
);
1721 tbl_update(VALUE hash
, VALUE key
, tbl_update_func func
, st_data_t optional_arg
)
1723 struct update_arg arg
= {
1724 .arg
= optional_arg
,
1728 .value
= (VALUE
)optional_arg
,
1731 int ret
= rb_hash_stlike_update(hash
, key
, tbl_update_modify
, (st_data_t
)&arg
);
1734 RB_OBJ_WRITTEN(hash
, Qundef
, arg
.key
);
1735 RB_OBJ_WRITTEN(hash
, Qundef
, arg
.value
);
1740 #define UPDATE_CALLBACK(iter_p, func) ((iter_p) ? func##_noinsert : func##_insert)
1742 #define RHASH_UPDATE_ITER(h, iter_p, key, func, a) do { \
1743 tbl_update((h), (key), UPDATE_CALLBACK(iter_p, func), (st_data_t)(a)); \
1746 #define RHASH_UPDATE(hash, key, func, arg) \
1747 RHASH_UPDATE_ITER(hash, hash_iterating_p(hash), key, func, arg)
1750 set_proc_default(VALUE hash
, VALUE proc
)
1752 if (rb_proc_lambda_p(proc
)) {
1753 int n
= rb_proc_arity(proc
);
1755 if (n
!= 2 && (n
>= 0 || n
< -3)) {
1756 if (n
< 0) n
= -n
-1;
1757 rb_raise(rb_eTypeError
, "default_proc takes two arguments (2 for %d)", n
);
1761 FL_SET_RAW(hash
, RHASH_PROC_DEFAULT
);
1762 RHASH_SET_IFNONE(hash
, proc
);
1767 * Hash.new(default_value = nil) -> new_hash
1768 * Hash.new {|hash, key| ... } -> new_hash
1770 * Returns a new empty +Hash+ object.
1772 * The initial default value and initial default proc for the new hash
1773 * depend on which form above was used. See {Default Values}[rdoc-ref:Hash@Default+Values].
1775 * If neither an argument nor a block given,
1776 * initializes both the default value and the default proc to <tt>nil</tt>:
1778 * h.default # => nil
1779 * h.default_proc # => nil
1781 * If argument <tt>default_value</tt> given but no block given,
1782 * initializes the default value to the given <tt>default_value</tt>
1783 * and the default proc to <tt>nil</tt>:
1784 * h = Hash.new(false)
1785 * h.default # => false
1786 * h.default_proc # => nil
1788 * If a block given but no argument, stores the block as the default proc
1789 * and sets the default value to <tt>nil</tt>:
1790 * h = Hash.new {|hash, key| "Default value for #{key}" }
1791 * h.default # => nil
1792 * h.default_proc.class # => Proc
1793 * h[:nosuch] # => "Default value for nosuch"
1797 rb_hash_initialize(int argc
, VALUE
*argv
, VALUE hash
)
1799 rb_hash_modify(hash
);
1801 if (rb_block_given_p()) {
1802 rb_check_arity(argc
, 0, 0);
1803 SET_PROC_DEFAULT(hash
, rb_block_proc());
1806 rb_check_arity(argc
, 0, 1);
1808 VALUE options
, ifnone
;
1809 rb_scan_args(argc
, argv
, "01:", &ifnone
, &options
);
1810 if (NIL_P(ifnone
) && !NIL_P(options
)) {
1812 rb_warn_deprecated_to_remove("3.4", "Calling Hash.new with keyword arguments", "Hash.new({ key: value })");
1814 RHASH_SET_IFNONE(hash
, ifnone
);
1820 static VALUE
rb_hash_to_a(VALUE hash
);
1824 * Hash[] -> new_empty_hash
1825 * Hash[hash] -> new_hash
1826 * Hash[ [*2_element_arrays] ] -> new_hash
1827 * Hash[*objects] -> new_hash
1829 * Returns a new +Hash+ object populated with the given objects, if any.
1832 * With no argument, returns a new empty +Hash+.
1834 * When the single given argument is a +Hash+, returns a new +Hash+
1835 * populated with the entries from the given +Hash+, excluding the
1836 * default value or proc.
1838 * h = {foo: 0, bar: 1, baz: 2}
1839 * Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
1841 * When the single given argument is an Array of 2-element Arrays,
1842 * returns a new +Hash+ object wherein each 2-element array forms a
1845 * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
1847 * When the argument count is an even number;
1848 * returns a new +Hash+ object wherein each successive pair of arguments
1849 * has become a key-value entry:
1851 * Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
1853 * Raises an exception if the argument list does not conform to any
1858 rb_hash_s_create(int argc
, VALUE
*argv
, VALUE klass
)
1863 tmp
= rb_hash_s_try_convert(Qnil
, argv
[0]);
1865 if (!RHASH_EMPTY_P(tmp
) && rb_hash_compare_by_id_p(tmp
)) {
1866 /* hash_copy for non-empty hash will copy compare_by_identity
1867 flag, but we don't want it copied. Work around by
1868 converting hash to flattened array and using that. */
1869 tmp
= rb_hash_to_a(tmp
);
1872 hash
= hash_alloc(klass
);
1873 if (!RHASH_EMPTY_P(tmp
))
1874 hash_copy(hash
, tmp
);
1879 tmp
= rb_check_array_type(argv
[0]);
1885 hash
= hash_alloc(klass
);
1886 for (i
= 0; i
< RARRAY_LEN(tmp
); ++i
) {
1887 VALUE e
= RARRAY_AREF(tmp
, i
);
1888 VALUE v
= rb_check_array_type(e
);
1889 VALUE key
, val
= Qnil
;
1892 rb_raise(rb_eArgError
, "wrong element type %s at %ld (expected array)",
1893 rb_builtin_class_name(e
), i
);
1895 switch (RARRAY_LEN(v
)) {
1897 rb_raise(rb_eArgError
, "invalid number of elements (%ld for 1..2)",
1900 val
= RARRAY_AREF(v
, 1);
1902 key
= RARRAY_AREF(v
, 0);
1903 rb_hash_aset(hash
, key
, val
);
1909 if (argc
% 2 != 0) {
1910 rb_raise(rb_eArgError
, "odd number of arguments for Hash");
1913 hash
= hash_alloc(klass
);
1914 rb_hash_bulk_insert(argc
, argv
, hash
);
1920 rb_to_hash_type(VALUE hash
)
1922 return rb_convert_type_with_id(hash
, T_HASH
, "Hash", idTo_hash
);
1924 #define to_hash rb_to_hash_type
1927 rb_check_hash_type(VALUE hash
)
1929 return rb_check_convert_type_with_id(hash
, T_HASH
, "Hash", idTo_hash
);
1934 * Hash.try_convert(obj) -> obj, new_hash, or nil
1936 * If +obj+ is a +Hash+ object, returns +obj+.
1938 * Otherwise if +obj+ responds to <tt>:to_hash</tt>,
1939 * calls <tt>obj.to_hash</tt> and returns the result.
1941 * Returns +nil+ if +obj+ does not respond to <tt>:to_hash</tt>
1943 * Raises an exception unless <tt>obj.to_hash</tt> returns a +Hash+ object.
1946 rb_hash_s_try_convert(VALUE dummy
, VALUE hash
)
1948 return rb_check_hash_type(hash
);
1953 * Hash.ruby2_keywords_hash?(hash) -> true or false
1955 * Checks if a given hash is flagged by Module#ruby2_keywords (or
1956 * Proc#ruby2_keywords).
1957 * This method is not for casual use; debugging, researching, and
1958 * some truly necessary cases like serialization of arguments.
1960 * ruby2_keywords def foo(*args)
1961 * Hash.ruby2_keywords_hash?(args.last)
1963 * foo(k: 1) #=> true
1964 * foo({k: 1}) #=> false
1967 rb_hash_s_ruby2_keywords_hash_p(VALUE dummy
, VALUE hash
)
1969 Check_Type(hash
, T_HASH
);
1970 return RBOOL(RHASH(hash
)->basic
.flags
& RHASH_PASS_AS_KEYWORDS
);
1975 * Hash.ruby2_keywords_hash(hash) -> hash
1977 * Duplicates a given hash and adds a ruby2_keywords flag.
1978 * This method is not for casual use; debugging, researching, and
1979 * some truly necessary cases like deserialization of arguments.
1982 * h = Hash.ruby2_keywords_hash(h)
1986 * foo(*[h]) #=> 1 with neither a warning or an error
1989 rb_hash_s_ruby2_keywords_hash(VALUE dummy
, VALUE hash
)
1991 Check_Type(hash
, T_HASH
);
1992 VALUE tmp
= rb_hash_dup(hash
);
1993 if (RHASH_EMPTY_P(hash
) && rb_hash_compare_by_id_p(hash
)) {
1994 rb_hash_compare_by_id(tmp
);
1996 RHASH(tmp
)->basic
.flags
|= RHASH_PASS_AS_KEYWORDS
;
2006 rb_hash_rehash_i(VALUE key
, VALUE value
, VALUE arg
)
2008 if (RHASH_AR_TABLE_P(arg
)) {
2009 ar_insert(arg
, (st_data_t
)key
, (st_data_t
)value
);
2012 st_insert(RHASH_ST_TABLE(arg
), (st_data_t
)key
, (st_data_t
)value
);
2019 * hash.rehash -> self
2021 * Rebuilds the hash table by recomputing the hash index for each key;
2022 * returns <tt>self</tt>.
2024 * The hash table becomes invalid if the hash value of a key
2025 * has changed after the entry was created.
2026 * See {Modifying an Active Hash Key}[rdoc-ref:Hash@Modifying+an+Active+Hash+Key].
2030 rb_hash_rehash(VALUE hash
)
2035 if (hash_iterating_p(hash
)) {
2036 rb_raise(rb_eRuntimeError
, "rehash during iteration");
2038 rb_hash_modify_check(hash
);
2039 if (RHASH_AR_TABLE_P(hash
)) {
2040 tmp
= hash_alloc(0);
2041 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
2043 hash_ar_free_and_clear_table(hash
);
2046 else if (RHASH_ST_TABLE_P(hash
)) {
2047 st_table
*old_tab
= RHASH_ST_TABLE(hash
);
2048 tmp
= hash_alloc(0);
2050 hash_st_table_init(tmp
, old_tab
->type
, old_tab
->num_entries
);
2051 tbl
= RHASH_ST_TABLE(tmp
);
2053 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
2056 RHASH_ST_TABLE_SET(hash
, tbl
);
2057 RHASH_ST_CLEAR(tmp
);
2064 call_default_proc(VALUE proc
, VALUE hash
, VALUE key
)
2066 VALUE args
[2] = {hash
, key
};
2067 return rb_proc_call_with_block(proc
, 2, args
, Qnil
);
2071 rb_hash_default_unredefined(VALUE hash
)
2073 VALUE klass
= RBASIC_CLASS(hash
);
2074 if (LIKELY(klass
== rb_cHash
)) {
2075 return !!BASIC_OP_UNREDEFINED_P(BOP_DEFAULT
, HASH_REDEFINED_OP_FLAG
);
2078 return LIKELY(rb_method_basic_definition_p(klass
, id_default
));
2083 rb_hash_default_value(VALUE hash
, VALUE key
)
2085 RUBY_ASSERT(RB_TYPE_P(hash
, T_HASH
));
2087 if (LIKELY(rb_hash_default_unredefined(hash
))) {
2088 VALUE ifnone
= RHASH_IFNONE(hash
);
2089 if (LIKELY(!FL_TEST_RAW(hash
, RHASH_PROC_DEFAULT
))) return ifnone
;
2090 if (UNDEF_P(key
)) return Qnil
;
2091 return call_default_proc(ifnone
, hash
, key
);
2094 return rb_funcall(hash
, id_default
, 1, key
);
2099 hash_stlike_lookup(VALUE hash
, st_data_t key
, st_data_t
*pval
)
2103 if (RHASH_AR_TABLE_P(hash
)) {
2104 return ar_lookup(hash
, key
, pval
);
2107 extern st_index_t
rb_iseq_cdhash_hash(VALUE
);
2108 RUBY_ASSERT(RHASH_ST_TABLE(hash
)->type
->hash
== rb_any_hash
||
2109 RHASH_ST_TABLE(hash
)->type
->hash
== rb_ident_hash
||
2110 RHASH_ST_TABLE(hash
)->type
->hash
== rb_iseq_cdhash_hash
);
2111 return st_lookup(RHASH_ST_TABLE(hash
), key
, pval
);
2116 rb_hash_stlike_lookup(VALUE hash
, st_data_t key
, st_data_t
*pval
)
2118 return hash_stlike_lookup(hash
, key
, pval
);
2123 * hash[key] -> value
2125 * Returns the value associated with the given +key+, if found:
2126 * h = {foo: 0, bar: 1, baz: 2}
2129 * If +key+ is not found, returns a default value
2130 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2131 * h = {foo: 0, bar: 1, baz: 2}
2132 * h[:nosuch] # => nil
2136 rb_hash_aref(VALUE hash
, VALUE key
)
2140 if (hash_stlike_lookup(hash
, key
, &val
)) {
2144 return rb_hash_default_value(hash
, key
);
2149 rb_hash_lookup2(VALUE hash
, VALUE key
, VALUE def
)
2153 if (hash_stlike_lookup(hash
, key
, &val
)) {
2157 return def
; /* without Hash#default */
2162 rb_hash_lookup(VALUE hash
, VALUE key
)
2164 return rb_hash_lookup2(hash
, key
, Qnil
);
2169 * hash.fetch(key) -> object
2170 * hash.fetch(key, default_value) -> object
2171 * hash.fetch(key) {|key| ... } -> object
2173 * Returns the value for the given +key+, if found.
2174 * h = {foo: 0, bar: 1, baz: 2}
2175 * h.fetch(:bar) # => 1
2177 * If +key+ is not found and no block was given,
2178 * returns +default_value+:
2179 * {}.fetch(:nosuch, :default) # => :default
2181 * If +key+ is not found and a block was given,
2182 * yields +key+ to the block and returns the block's return value:
2183 * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2185 * Raises KeyError if neither +default_value+ nor a block was given.
2187 * Note that this method does not use the values of either #default or #default_proc.
2191 rb_hash_fetch_m(int argc
, VALUE
*argv
, VALUE hash
)
2197 rb_check_arity(argc
, 1, 2);
2200 block_given
= rb_block_given_p();
2201 if (block_given
&& argc
== 2) {
2202 rb_warn("block supersedes default value argument");
2205 if (hash_stlike_lookup(hash
, key
, &val
)) {
2210 return rb_yield(key
);
2212 else if (argc
== 1) {
2213 VALUE desc
= rb_protect(rb_inspect
, key
, 0);
2215 desc
= rb_any_to_s(key
);
2217 desc
= rb_str_ellipsize(desc
, 65);
2218 rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE
, desc
), hash
, key
);
2227 rb_hash_fetch(VALUE hash
, VALUE key
)
2229 return rb_hash_fetch_m(1, &key
, hash
);
2234 * hash.default -> object
2235 * hash.default(key) -> object
2237 * Returns the default value for the given +key+.
2238 * The returned value will be determined either by the default proc or by the default value.
2239 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2241 * With no argument, returns the current default value:
2243 * h.default # => nil
2245 * If +key+ is given, returns the default value for +key+,
2246 * regardless of whether that key exists:
2247 * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2249 * h.default(:foo) # => "No key foo"
2253 rb_hash_default(int argc
, VALUE
*argv
, VALUE hash
)
2257 rb_check_arity(argc
, 0, 1);
2258 ifnone
= RHASH_IFNONE(hash
);
2259 if (FL_TEST(hash
, RHASH_PROC_DEFAULT
)) {
2260 if (argc
== 0) return Qnil
;
2261 return call_default_proc(ifnone
, hash
, argv
[0]);
2268 * hash.default = value -> object
2270 * Sets the default value to +value+; returns +value+:
2272 * h.default # => nil
2273 * h.default = false # => false
2274 * h.default # => false
2276 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2280 rb_hash_set_default(VALUE hash
, VALUE ifnone
)
2282 rb_hash_modify_check(hash
);
2283 SET_DEFAULT(hash
, ifnone
);
2289 * hash.default_proc -> proc or nil
2291 * Returns the default proc for +self+
2292 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2294 * h.default_proc # => nil
2295 * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2296 * h.default_proc.class # => Proc
2300 rb_hash_default_proc(VALUE hash
)
2302 if (FL_TEST(hash
, RHASH_PROC_DEFAULT
)) {
2303 return RHASH_IFNONE(hash
);
2310 * hash.default_proc = proc -> proc
2312 * Sets the default proc for +self+ to +proc+
2313 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2315 * h.default_proc # => nil
2316 * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2317 * h.default_proc.class # => Proc
2318 * h.default_proc = nil
2319 * h.default_proc # => nil
2323 rb_hash_set_default_proc(VALUE hash
, VALUE proc
)
2327 rb_hash_modify_check(hash
);
2329 SET_DEFAULT(hash
, proc
);
2332 b
= rb_check_convert_type_with_id(proc
, T_DATA
, "Proc", idTo_proc
);
2333 if (NIL_P(b
) || !rb_obj_is_proc(b
)) {
2334 rb_raise(rb_eTypeError
,
2335 "wrong default_proc type %s (expected Proc)",
2336 rb_obj_classname(proc
));
2339 SET_PROC_DEFAULT(hash
, proc
);
2344 key_i(VALUE key
, VALUE value
, VALUE arg
)
2346 VALUE
*args
= (VALUE
*)arg
;
2348 if (rb_equal(value
, args
[0])) {
2357 * hash.key(value) -> key or nil
2359 * Returns the key for the first-found entry with the given +value+
2360 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2361 * h = {foo: 0, bar: 2, baz: 2}
2362 * h.key(0) # => :foo
2363 * h.key(2) # => :bar
2365 * Returns +nil+ if no such value is found.
2369 rb_hash_key(VALUE hash
, VALUE value
)
2376 rb_hash_foreach(hash
, key_i
, (VALUE
)args
);
2382 rb_hash_stlike_delete(VALUE hash
, st_data_t
*pkey
, st_data_t
*pval
)
2384 if (RHASH_AR_TABLE_P(hash
)) {
2385 return ar_delete(hash
, pkey
, pval
);
2388 return st_delete(RHASH_ST_TABLE(hash
), pkey
, pval
);
2393 * delete a specified entry by a given key.
2394 * if there is the corresponding entry, return a value of the entry.
2395 * if there is no corresponding entry, return Qundef.
2398 rb_hash_delete_entry(VALUE hash
, VALUE key
)
2400 st_data_t ktmp
= (st_data_t
)key
, val
;
2402 if (rb_hash_stlike_delete(hash
, &ktmp
, &val
)) {
2411 * delete a specified entry by a given key.
2412 * if there is the corresponding entry, return a value of the entry.
2413 * if there is no corresponding entry, return Qnil.
2416 rb_hash_delete(VALUE hash
, VALUE key
)
2418 VALUE deleted_value
= rb_hash_delete_entry(hash
, key
);
2420 if (!UNDEF_P(deleted_value
)) { /* likely pass */
2421 return deleted_value
;
2430 * hash.delete(key) -> value or nil
2431 * hash.delete(key) {|key| ... } -> object
2433 * Deletes the entry for the given +key+ and returns its associated value.
2435 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
2436 * h = {foo: 0, bar: 1, baz: 2}
2437 * h.delete(:bar) # => 1
2438 * h # => {:foo=>0, :baz=>2}
2440 * If no block given and +key+ is not found, returns +nil+.
2442 * If a block is given and +key+ is found, ignores the block,
2443 * deletes the entry, and returns the associated value:
2444 * h = {foo: 0, bar: 1, baz: 2}
2445 * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2446 * h # => {:foo=>0, :bar=>1}
2448 * If a block is given and +key+ is not found,
2449 * calls the block and returns the block's return value:
2450 * h = {foo: 0, bar: 1, baz: 2}
2451 * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2452 * h # => {:foo=>0, :bar=>1, :baz=>2}
2456 rb_hash_delete_m(VALUE hash
, VALUE key
)
2460 rb_hash_modify_check(hash
);
2461 val
= rb_hash_delete_entry(hash
, key
);
2463 if (!UNDEF_P(val
)) {
2464 compact_after_delete(hash
);
2468 if (rb_block_given_p()) {
2469 return rb_yield(key
);
2483 shift_i_safe(VALUE key
, VALUE value
, VALUE arg
)
2485 struct shift_var
*var
= (struct shift_var
*)arg
;
2494 * hash.shift -> [key, value] or nil
2496 * Removes the first hash entry
2497 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]);
2498 * returns a 2-element Array containing the removed key and value:
2499 * h = {foo: 0, bar: 1, baz: 2}
2500 * h.shift # => [:foo, 0]
2501 * h # => {:bar=>1, :baz=>2}
2503 * Returns nil if the hash is empty.
2507 rb_hash_shift(VALUE hash
)
2509 struct shift_var var
;
2511 rb_hash_modify_check(hash
);
2512 if (RHASH_AR_TABLE_P(hash
)) {
2514 if (!hash_iterating_p(hash
)) {
2515 if (ar_shift(hash
, &var
.key
, &var
.val
)) {
2516 return rb_assoc_new(var
.key
, var
.val
);
2520 rb_hash_foreach(hash
, shift_i_safe
, (VALUE
)&var
);
2521 if (!UNDEF_P(var
.key
)) {
2522 rb_hash_delete_entry(hash
, var
.key
);
2523 return rb_assoc_new(var
.key
, var
.val
);
2527 if (RHASH_ST_TABLE_P(hash
)) {
2529 if (!hash_iterating_p(hash
)) {
2530 if (st_shift(RHASH_ST_TABLE(hash
), &var
.key
, &var
.val
)) {
2531 return rb_assoc_new(var
.key
, var
.val
);
2535 rb_hash_foreach(hash
, shift_i_safe
, (VALUE
)&var
);
2536 if (!UNDEF_P(var
.key
)) {
2537 rb_hash_delete_entry(hash
, var
.key
);
2538 return rb_assoc_new(var
.key
, var
.val
);
2546 delete_if_i(VALUE key
, VALUE value
, VALUE hash
)
2548 if (RTEST(rb_yield_values(2, key
, value
))) {
2549 rb_hash_modify(hash
);
2556 hash_enum_size(VALUE hash
, VALUE args
, VALUE eobj
)
2558 return rb_hash_size(hash
);
2563 * hash.delete_if {|key, value| ... } -> self
2564 * hash.delete_if -> new_enumerator
2566 * If a block given, calls the block with each key-value pair;
2567 * deletes each entry for which the block returns a truthy value;
2569 * h = {foo: 0, bar: 1, baz: 2}
2570 * h.delete_if {|key, value| value > 0 } # => {:foo=>0}
2572 * If no block given, returns a new Enumerator:
2573 * h = {foo: 0, bar: 1, baz: 2}
2574 * e = h.delete_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:delete_if>
2575 * e.each { |key, value| value > 0 } # => {:foo=>0}
2579 rb_hash_delete_if(VALUE hash
)
2581 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2582 rb_hash_modify_check(hash
);
2583 if (!RHASH_TABLE_EMPTY_P(hash
)) {
2584 rb_hash_foreach(hash
, delete_if_i
, hash
);
2585 compact_after_delete(hash
);
2592 * hash.reject! {|key, value| ... } -> self or nil
2593 * hash.reject! -> new_enumerator
2595 * Returns +self+, whose remaining entries are those
2596 * for which the block returns +false+ or +nil+:
2597 * h = {foo: 0, bar: 1, baz: 2}
2598 * h.reject! {|key, value| value < 2 } # => {:baz=>2}
2600 * Returns +nil+ if no entries are removed.
2602 * Returns a new Enumerator if no block given:
2603 * h = {foo: 0, bar: 1, baz: 2}
2604 * e = h.reject! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject!>
2605 * e.each {|key, value| key.start_with?('b') } # => {:foo=>0}
2609 rb_hash_reject_bang(VALUE hash
)
2613 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2614 rb_hash_modify(hash
);
2615 n
= RHASH_SIZE(hash
);
2616 if (!n
) return Qnil
;
2617 rb_hash_foreach(hash
, delete_if_i
, hash
);
2618 if (n
== RHASH_SIZE(hash
)) return Qnil
;
2624 * hash.reject {|key, value| ... } -> new_hash
2625 * hash.reject -> new_enumerator
2627 * Returns a new +Hash+ object whose entries are all those
2628 * from +self+ for which the block returns +false+ or +nil+:
2629 * h = {foo: 0, bar: 1, baz: 2}
2630 * h1 = h.reject {|key, value| key.start_with?('b') }
2633 * Returns a new Enumerator if no block given:
2634 * h = {foo: 0, bar: 1, baz: 2}
2635 * e = h.reject # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject>
2636 * h1 = e.each {|key, value| key.start_with?('b') }
2641 rb_hash_reject(VALUE hash
)
2645 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2646 result
= hash_dup_with_compare_by_id(hash
);
2647 if (!RHASH_EMPTY_P(hash
)) {
2648 rb_hash_foreach(result
, delete_if_i
, result
);
2649 compact_after_delete(result
);
2656 * hash.slice(*keys) -> new_hash
2658 * Returns a new +Hash+ object containing the entries for the given +keys+:
2659 * h = {foo: 0, bar: 1, baz: 2}
2660 * h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
2662 * Any given +keys+ that are not found are ignored.
2666 rb_hash_slice(int argc
, VALUE
*argv
, VALUE hash
)
2669 VALUE key
, value
, result
;
2671 if (argc
== 0 || RHASH_EMPTY_P(hash
)) {
2672 return copy_compare_by_id(rb_hash_new(), hash
);
2674 result
= copy_compare_by_id(rb_hash_new_with_size(argc
), hash
);
2676 for (i
= 0; i
< argc
; i
++) {
2678 value
= rb_hash_lookup2(hash
, key
, Qundef
);
2679 if (!UNDEF_P(value
))
2680 rb_hash_aset(result
, key
, value
);
2688 * hsh.except(*keys) -> a_hash
2690 * Returns a new +Hash+ excluding entries for the given +keys+:
2691 * h = { a: 100, b: 200, c: 300 }
2692 * h.except(:a) #=> {:b=>200, :c=>300}
2694 * Any given +keys+ that are not found are ignored.
2698 rb_hash_except(int argc
, VALUE
*argv
, VALUE hash
)
2703 result
= hash_dup_with_compare_by_id(hash
);
2705 for (i
= 0; i
< argc
; i
++) {
2707 rb_hash_delete(result
, key
);
2709 compact_after_delete(result
);
2716 * hash.values_at(*keys) -> new_array
2718 * Returns a new Array containing values for the given +keys+:
2719 * h = {foo: 0, bar: 1, baz: 2}
2720 * h.values_at(:baz, :foo) # => [2, 0]
2722 * The {default values}[rdoc-ref:Hash@Default+Values] are returned
2723 * for any keys that are not found:
2724 * h.values_at(:hello, :foo) # => [nil, 0]
2728 rb_hash_values_at(int argc
, VALUE
*argv
, VALUE hash
)
2730 VALUE result
= rb_ary_new2(argc
);
2733 for (i
=0; i
<argc
; i
++) {
2734 rb_ary_push(result
, rb_hash_aref(hash
, argv
[i
]));
2741 * hash.fetch_values(*keys) -> new_array
2742 * hash.fetch_values(*keys) {|key| ... } -> new_array
2744 * Returns a new Array containing the values associated with the given keys *keys:
2745 * h = {foo: 0, bar: 1, baz: 2}
2746 * h.fetch_values(:baz, :foo) # => [2, 0]
2748 * Returns a new empty Array if no arguments given.
2750 * When a block is given, calls the block with each missing key,
2751 * treating the block's return value as the value for that key:
2752 * h = {foo: 0, bar: 1, baz: 2}
2753 * values = h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2754 * values # => [1, 0, "bad", "bam"]
2756 * When no block is given, raises an exception if any given key is not found.
2760 rb_hash_fetch_values(int argc
, VALUE
*argv
, VALUE hash
)
2762 VALUE result
= rb_ary_new2(argc
);
2765 for (i
=0; i
<argc
; i
++) {
2766 rb_ary_push(result
, rb_hash_fetch(hash
, argv
[i
]));
2772 keep_if_i(VALUE key
, VALUE value
, VALUE hash
)
2774 if (!RTEST(rb_yield_values(2, key
, value
))) {
2775 rb_hash_modify(hash
);
2783 * hash.select {|key, value| ... } -> new_hash
2784 * hash.select -> new_enumerator
2786 * Returns a new +Hash+ object whose entries are those for which the block returns a truthy value:
2787 * h = {foo: 0, bar: 1, baz: 2}
2788 * h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2790 * Returns a new Enumerator if no block given:
2791 * h = {foo: 0, bar: 1, baz: 2}
2792 * e = h.select # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select>
2793 * e.each {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2797 rb_hash_select(VALUE hash
)
2801 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2802 result
= hash_dup_with_compare_by_id(hash
);
2803 if (!RHASH_EMPTY_P(hash
)) {
2804 rb_hash_foreach(result
, keep_if_i
, result
);
2805 compact_after_delete(result
);
2812 * hash.select! {|key, value| ... } -> self or nil
2813 * hash.select! -> new_enumerator
2815 * Returns +self+, whose entries are those for which the block returns a truthy value:
2816 * h = {foo: 0, bar: 1, baz: 2}
2817 * h.select! {|key, value| value < 2 } => {:foo=>0, :bar=>1}
2819 * Returns +nil+ if no entries were removed.
2821 * Returns a new Enumerator if no block given:
2822 * h = {foo: 0, bar: 1, baz: 2}
2823 * e = h.select! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select!>
2824 * e.each { |key, value| value < 2 } # => {:foo=>0, :bar=>1}
2828 rb_hash_select_bang(VALUE hash
)
2832 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2833 rb_hash_modify_check(hash
);
2834 n
= RHASH_SIZE(hash
);
2835 if (!n
) return Qnil
;
2836 rb_hash_foreach(hash
, keep_if_i
, hash
);
2837 if (n
== RHASH_SIZE(hash
)) return Qnil
;
2843 * hash.keep_if {|key, value| ... } -> self
2844 * hash.keep_if -> new_enumerator
2846 * Calls the block for each key-value pair;
2847 * retains the entry if the block returns a truthy value;
2848 * otherwise deletes the entry; returns +self+.
2849 * h = {foo: 0, bar: 1, baz: 2}
2850 * h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2852 * Returns a new Enumerator if no block given:
2853 * h = {foo: 0, bar: 1, baz: 2}
2854 * e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if>
2855 * e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2859 rb_hash_keep_if(VALUE hash
)
2861 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2862 rb_hash_modify_check(hash
);
2863 if (!RHASH_TABLE_EMPTY_P(hash
)) {
2864 rb_hash_foreach(hash
, keep_if_i
, hash
);
2870 clear_i(VALUE key
, VALUE value
, VALUE dummy
)
2877 * hash.clear -> self
2879 * Removes all hash entries; returns +self+.
2883 rb_hash_clear(VALUE hash
)
2885 rb_hash_modify_check(hash
);
2887 if (hash_iterating_p(hash
)) {
2888 rb_hash_foreach(hash
, clear_i
, 0);
2890 else if (RHASH_AR_TABLE_P(hash
)) {
2894 st_clear(RHASH_ST_TABLE(hash
));
2895 compact_after_delete(hash
);
2902 hash_aset(st_data_t
*key
, st_data_t
*val
, struct update_arg
*arg
, int existing
)
2909 rb_hash_key_str(VALUE key
)
2911 if (!RB_FL_ANY_RAW(key
, FL_EXIVAR
) && RBASIC_CLASS(key
) == rb_cString
) {
2912 return rb_fstring(key
);
2915 return rb_str_new_frozen(key
);
2920 hash_aset_str(st_data_t
*key
, st_data_t
*val
, struct update_arg
*arg
, int existing
)
2922 if (!existing
&& !RB_OBJ_FROZEN(*key
)) {
2923 *key
= rb_hash_key_str(*key
);
2925 return hash_aset(key
, val
, arg
, existing
);
2928 NOINSERT_UPDATE_CALLBACK(hash_aset
)
2929 NOINSERT_UPDATE_CALLBACK(hash_aset_str
)
2933 * hash[key] = value -> value
2934 * hash.store(key, value)
2936 * Associates the given +value+ with the given +key+; returns +value+.
2938 * If the given +key+ exists, replaces its value with the given +value+;
2939 * the ordering is not affected
2940 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2941 * h = {foo: 0, bar: 1}
2942 * h[:foo] = 2 # => 2
2943 * h.store(:bar, 3) # => 3
2944 * h # => {:foo=>2, :bar=>3}
2946 * If +key+ does not exist, adds the +key+ and +value+;
2947 * the new entry is last in the order
2948 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2949 * h = {foo: 0, bar: 1}
2950 * h[:baz] = 2 # => 2
2951 * h.store(:bat, 3) # => 3
2952 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
2956 rb_hash_aset(VALUE hash
, VALUE key
, VALUE val
)
2958 bool iter_p
= hash_iterating_p(hash
);
2960 rb_hash_modify(hash
);
2962 if (!RHASH_STRING_KEY_P(hash
, key
)) {
2963 RHASH_UPDATE_ITER(hash
, iter_p
, key
, hash_aset
, val
);
2966 RHASH_UPDATE_ITER(hash
, iter_p
, key
, hash_aset_str
, val
);
2973 * hash.replace(other_hash) -> self
2975 * Replaces the entire contents of +self+ with the contents of +other_hash+;
2977 * h = {foo: 0, bar: 1, baz: 2}
2978 * h.replace({bat: 3, bam: 4}) # => {:bat=>3, :bam=>4}
2982 rb_hash_replace(VALUE hash
, VALUE hash2
)
2984 rb_hash_modify_check(hash
);
2985 if (hash
== hash2
) return hash
;
2986 if (hash_iterating_p(hash
)) {
2987 rb_raise(rb_eRuntimeError
, "can't replace hash during iteration");
2989 hash2
= to_hash(hash2
);
2991 COPY_DEFAULT(hash
, hash2
);
2993 if (RHASH_AR_TABLE_P(hash
)) {
2994 hash_ar_free_and_clear_table(hash
);
2997 hash_st_free_and_clear_table(hash
);
3000 hash_copy(hash
, hash2
);
3007 * hash.length -> integer
3008 * hash.size -> integer
3010 * Returns the count of entries in +self+:
3012 * {foo: 0, bar: 1, baz: 2}.length # => 3
3017 rb_hash_size(VALUE hash
)
3019 return INT2FIX(RHASH_SIZE(hash
));
3023 rb_hash_size_num(VALUE hash
)
3025 return (long)RHASH_SIZE(hash
);
3030 * hash.empty? -> true or false
3032 * Returns +true+ if there are no hash entries, +false+ otherwise:
3033 * {}.empty? # => true
3034 * {foo: 0, bar: 1, baz: 2}.empty? # => false
3038 rb_hash_empty_p(VALUE hash
)
3040 return RBOOL(RHASH_EMPTY_P(hash
));
3044 each_value_i(VALUE key
, VALUE value
, VALUE _
)
3052 * hash.each_value {|value| ... } -> self
3053 * hash.each_value -> new_enumerator
3055 * Calls the given block with each value; returns +self+:
3056 * h = {foo: 0, bar: 1, baz: 2}
3057 * h.each_value {|value| puts value } # => {:foo=>0, :bar=>1, :baz=>2}
3063 * Returns a new Enumerator if no block given:
3064 * h = {foo: 0, bar: 1, baz: 2}
3065 * e = h.each_value # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_value>
3066 * h1 = e.each {|value| puts value }
3067 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3075 rb_hash_each_value(VALUE hash
)
3077 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3078 rb_hash_foreach(hash
, each_value_i
, 0);
3083 each_key_i(VALUE key
, VALUE value
, VALUE _
)
3091 * hash.each_key {|key| ... } -> self
3092 * hash.each_key -> new_enumerator
3094 * Calls the given block with each key; returns +self+:
3095 * h = {foo: 0, bar: 1, baz: 2}
3096 * h.each_key {|key| puts key } # => {:foo=>0, :bar=>1, :baz=>2}
3102 * Returns a new Enumerator if no block given:
3103 * h = {foo: 0, bar: 1, baz: 2}
3104 * e = h.each_key # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_key>
3105 * h1 = e.each {|key| puts key }
3106 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3113 rb_hash_each_key(VALUE hash
)
3115 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3116 rb_hash_foreach(hash
, each_key_i
, 0);
3121 each_pair_i(VALUE key
, VALUE value
, VALUE _
)
3123 rb_yield(rb_assoc_new(key
, value
));
3128 each_pair_i_fast(VALUE key
, VALUE value
, VALUE _
)
3133 rb_yield_values2(2, argv
);
3139 * hash.each {|key, value| ... } -> self
3140 * hash.each_pair {|key, value| ... } -> self
3141 * hash.each -> new_enumerator
3142 * hash.each_pair -> new_enumerator
3144 * Calls the given block with each key-value pair; returns +self+:
3145 * h = {foo: 0, bar: 1, baz: 2}
3146 * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}
3152 * Returns a new Enumerator if no block given:
3153 * h = {foo: 0, bar: 1, baz: 2}
3154 * e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
3155 * h1 = e.each {|key, value| puts "#{key}: #{value}"}
3156 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3164 rb_hash_each_pair(VALUE hash
)
3166 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3167 if (rb_block_pair_yield_optimizable())
3168 rb_hash_foreach(hash
, each_pair_i_fast
, 0);
3170 rb_hash_foreach(hash
, each_pair_i
, 0);
3174 struct transform_keys_args
{
3181 transform_keys_hash_i(VALUE key
, VALUE value
, VALUE transarg
)
3183 struct transform_keys_args
*p
= (void *)transarg
;
3184 VALUE trans
= p
->trans
, result
= p
->result
;
3185 VALUE new_key
= rb_hash_lookup2(trans
, key
, Qundef
);
3186 if (UNDEF_P(new_key
)) {
3188 new_key
= rb_yield(key
);
3192 rb_hash_aset(result
, new_key
, value
);
3197 transform_keys_i(VALUE key
, VALUE value
, VALUE result
)
3199 VALUE new_key
= rb_yield(key
);
3200 rb_hash_aset(result
, new_key
, value
);
3206 * hash.transform_keys {|key| ... } -> new_hash
3207 * hash.transform_keys(hash2) -> new_hash
3208 * hash.transform_keys(hash2) {|other_key| ...} -> new_hash
3209 * hash.transform_keys -> new_enumerator
3211 * Returns a new +Hash+ object; each entry has:
3212 * * A key provided by the block.
3213 * * The value from +self+.
3215 * An optional hash argument can be provided to map keys to new keys.
3216 * Any key not given will be mapped using the provided block,
3217 * or remain the same if no block is given.
3220 * h = {foo: 0, bar: 1, baz: 2}
3221 * h1 = h.transform_keys {|key| key.to_s }
3222 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3224 * h.transform_keys(foo: :bar, bar: :foo)
3225 * #=> {bar: 0, foo: 1, baz: 2}
3227 * h.transform_keys(foo: :hello, &:to_s)
3228 * #=> {:hello=>0, "bar"=>1, "baz"=>2}
3230 * Overwrites values for duplicate keys:
3231 * h = {foo: 0, bar: 1, baz: 2}
3232 * h1 = h.transform_keys {|key| :bat }
3235 * Returns a new Enumerator if no block given:
3236 * h = {foo: 0, bar: 1, baz: 2}
3237 * e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
3238 * h1 = e.each { |key| key.to_s }
3239 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3242 rb_hash_transform_keys(int argc
, VALUE
*argv
, VALUE hash
)
3245 struct transform_keys_args transarg
= {0};
3247 argc
= rb_check_arity(argc
, 0, 1);
3249 transarg
.trans
= to_hash(argv
[0]);
3250 transarg
.block_given
= rb_block_given_p();
3253 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3255 result
= rb_hash_new();
3256 if (!RHASH_EMPTY_P(hash
)) {
3257 if (transarg
.trans
) {
3258 transarg
.result
= result
;
3259 rb_hash_foreach(hash
, transform_keys_hash_i
, (VALUE
)&transarg
);
3262 rb_hash_foreach(hash
, transform_keys_i
, result
);
3269 static int flatten_i(VALUE key
, VALUE val
, VALUE ary
);
3273 * hash.transform_keys! {|key| ... } -> self
3274 * hash.transform_keys!(hash2) -> self
3275 * hash.transform_keys!(hash2) {|other_key| ...} -> self
3276 * hash.transform_keys! -> new_enumerator
3278 * Same as Hash#transform_keys but modifies the receiver in place
3279 * instead of returning a new hash.
3282 rb_hash_transform_keys_bang(int argc
, VALUE
*argv
, VALUE hash
)
3285 int block_given
= 0;
3287 argc
= rb_check_arity(argc
, 0, 1);
3289 trans
= to_hash(argv
[0]);
3290 block_given
= rb_block_given_p();
3293 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3295 rb_hash_modify_check(hash
);
3296 if (!RHASH_TABLE_EMPTY_P(hash
)) {
3298 VALUE new_keys
= hash_alloc(0);
3299 VALUE pairs
= rb_ary_hidden_new(RHASH_SIZE(hash
) * 2);
3300 rb_hash_foreach(hash
, flatten_i
, pairs
);
3301 for (i
= 0; i
< RARRAY_LEN(pairs
); i
+= 2) {
3302 VALUE key
= RARRAY_AREF(pairs
, i
), new_key
, val
;
3305 new_key
= rb_yield(key
);
3307 else if (!UNDEF_P(new_key
= rb_hash_lookup2(trans
, key
, Qundef
))) {
3308 /* use the transformed key */
3310 else if (block_given
) {
3311 new_key
= rb_yield(key
);
3316 val
= RARRAY_AREF(pairs
, i
+1);
3317 if (!hash_stlike_lookup(new_keys
, key
, NULL
)) {
3318 rb_hash_stlike_delete(hash
, &key
, NULL
);
3320 rb_hash_aset(hash
, new_key
, val
);
3321 rb_hash_aset(new_keys
, new_key
, Qnil
);
3323 rb_ary_clear(pairs
);
3324 rb_hash_clear(new_keys
);
3326 compact_after_delete(hash
);
3331 transform_values_foreach_func(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
3337 transform_values_foreach_replace(st_data_t
*key
, st_data_t
*value
, st_data_t argp
, int existing
)
3339 VALUE new_value
= rb_yield((VALUE
)*value
);
3340 VALUE hash
= (VALUE
)argp
;
3341 rb_hash_modify(hash
);
3342 RB_OBJ_WRITE(hash
, value
, new_value
);
3348 * hash.transform_values {|value| ... } -> new_hash
3349 * hash.transform_values -> new_enumerator
3351 * Returns a new +Hash+ object; each entry has:
3352 * * A key from +self+.
3353 * * A value provided by the block.
3356 * h = {foo: 0, bar: 1, baz: 2}
3357 * h1 = h.transform_values {|value| value * 100}
3358 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3360 * Returns a new Enumerator if no block given:
3361 * h = {foo: 0, bar: 1, baz: 2}
3362 * e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values>
3363 * h1 = e.each { |value| value * 100}
3364 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3367 rb_hash_transform_values(VALUE hash
)
3371 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3372 result
= hash_dup_with_compare_by_id(hash
);
3373 SET_DEFAULT(result
, Qnil
);
3375 if (!RHASH_EMPTY_P(hash
)) {
3376 rb_hash_stlike_foreach_with_replace(result
, transform_values_foreach_func
, transform_values_foreach_replace
, result
);
3377 compact_after_delete(result
);
3385 * hash.transform_values! {|value| ... } -> self
3386 * hash.transform_values! -> new_enumerator
3388 * Returns +self+, whose keys are unchanged, and whose values are determined by the given block.
3389 * h = {foo: 0, bar: 1, baz: 2}
3390 * h.transform_values! {|value| value * 100} # => {:foo=>0, :bar=>100, :baz=>200}
3392 * Returns a new Enumerator if no block given:
3393 * h = {foo: 0, bar: 1, baz: 2}
3394 * e = h.transform_values! # => #<Enumerator: {:foo=>0, :bar=>100, :baz=>200}:transform_values!>
3395 * h1 = e.each {|value| value * 100}
3396 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3399 rb_hash_transform_values_bang(VALUE hash
)
3401 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3402 rb_hash_modify_check(hash
);
3404 if (!RHASH_TABLE_EMPTY_P(hash
)) {
3405 rb_hash_stlike_foreach_with_replace(hash
, transform_values_foreach_func
, transform_values_foreach_replace
, hash
);
3412 to_a_i(VALUE key
, VALUE value
, VALUE ary
)
3414 rb_ary_push(ary
, rb_assoc_new(key
, value
));
3420 * hash.to_a -> new_array
3422 * Returns a new Array of 2-element Array objects;
3423 * each nested Array contains a key-value pair from +self+:
3424 * h = {foo: 0, bar: 1, baz: 2}
3425 * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3429 rb_hash_to_a(VALUE hash
)
3433 ary
= rb_ary_new_capa(RHASH_SIZE(hash
));
3434 rb_hash_foreach(hash
, to_a_i
, ary
);
3440 inspect_i(VALUE key
, VALUE value
, VALUE str
)
3444 str2
= rb_inspect(key
);
3445 if (RSTRING_LEN(str
) > 1) {
3446 rb_str_buf_cat_ascii(str
, ", ");
3449 rb_enc_copy(str
, str2
);
3451 rb_str_buf_append(str
, str2
);
3452 rb_str_buf_cat_ascii(str
, "=>");
3453 str2
= rb_inspect(value
);
3454 rb_str_buf_append(str
, str2
);
3460 inspect_hash(VALUE hash
, VALUE dummy
, int recur
)
3464 if (recur
) return rb_usascii_str_new2("{...}");
3465 str
= rb_str_buf_new2("{");
3466 rb_hash_foreach(hash
, inspect_i
, str
);
3467 rb_str_buf_cat2(str
, "}");
3474 * hash.inspect -> new_string
3476 * Returns a new String containing the hash entries:
3478 * h = {foo: 0, bar: 1, baz: 2}
3479 * h.inspect # => "{:foo=>0, :bar=>1, :baz=>2}"
3484 rb_hash_inspect(VALUE hash
)
3486 if (RHASH_EMPTY_P(hash
))
3487 return rb_usascii_str_new2("{}");
3488 return rb_exec_recursive(inspect_hash
, hash
, 0);
3493 * hash.to_hash -> self
3498 rb_hash_to_hash(VALUE hash
)
3504 rb_hash_set_pair(VALUE hash
, VALUE arg
)
3508 pair
= rb_check_array_type(arg
);
3510 rb_raise(rb_eTypeError
, "wrong element type %s (expected array)",
3511 rb_builtin_class_name(arg
));
3513 if (RARRAY_LEN(pair
) != 2) {
3514 rb_raise(rb_eArgError
, "element has wrong array length (expected 2, was %ld)",
3517 rb_hash_aset(hash
, RARRAY_AREF(pair
, 0), RARRAY_AREF(pair
, 1));
3522 to_h_i(VALUE key
, VALUE value
, VALUE hash
)
3524 rb_hash_set_pair(hash
, rb_yield_values(2, key
, value
));
3529 rb_hash_to_h_block(VALUE hash
)
3531 VALUE h
= rb_hash_new_with_size(RHASH_SIZE(hash
));
3532 rb_hash_foreach(hash
, to_h_i
, h
);
3538 * hash.to_h -> self or new_hash
3539 * hash.to_h {|key, value| ... } -> new_hash
3541 * For an instance of +Hash+, returns +self+.
3543 * For a subclass of +Hash+, returns a new +Hash+
3544 * containing the content of +self+.
3546 * When a block is given, returns a new +Hash+ object
3547 * whose content is based on the block;
3548 * the block should return a 2-element Array object
3549 * specifying the key-value pair to be included in the returned Array:
3550 * h = {foo: 0, bar: 1, baz: 2}
3551 * h1 = h.to_h {|key, value| [value, key] }
3552 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3556 rb_hash_to_h(VALUE hash
)
3558 if (rb_block_given_p()) {
3559 return rb_hash_to_h_block(hash
);
3561 if (rb_obj_class(hash
) != rb_cHash
) {
3562 const VALUE flags
= RBASIC(hash
)->flags
;
3563 hash
= hash_dup(hash
, rb_cHash
, flags
& RHASH_PROC_DEFAULT
);
3569 keys_i(VALUE key
, VALUE value
, VALUE ary
)
3571 rb_ary_push(ary
, key
);
3577 * hash.keys -> new_array
3579 * Returns a new Array containing all keys in +self+:
3580 * h = {foo: 0, bar: 1, baz: 2}
3581 * h.keys # => [:foo, :bar, :baz]
3585 rb_hash_keys(VALUE hash
)
3587 st_index_t size
= RHASH_SIZE(hash
);
3588 VALUE keys
= rb_ary_new_capa(size
);
3590 if (size
== 0) return keys
;
3592 if (ST_DATA_COMPATIBLE_P(VALUE
)) {
3593 RARRAY_PTR_USE(keys
, ptr
, {
3594 if (RHASH_AR_TABLE_P(hash
)) {
3595 size
= ar_keys(hash
, ptr
, size
);
3598 st_table
*table
= RHASH_ST_TABLE(hash
);
3599 size
= st_keys(table
, ptr
, size
);
3602 rb_gc_writebarrier_remember(keys
);
3603 rb_ary_set_len(keys
, size
);
3606 rb_hash_foreach(hash
, keys_i
, keys
);
3613 values_i(VALUE key
, VALUE value
, VALUE ary
)
3615 rb_ary_push(ary
, value
);
3621 * hash.values -> new_array
3623 * Returns a new Array containing all values in +self+:
3624 * h = {foo: 0, bar: 1, baz: 2}
3625 * h.values # => [0, 1, 2]
3629 rb_hash_values(VALUE hash
)
3632 st_index_t size
= RHASH_SIZE(hash
);
3634 values
= rb_ary_new_capa(size
);
3635 if (size
== 0) return values
;
3637 if (ST_DATA_COMPATIBLE_P(VALUE
)) {
3638 if (RHASH_AR_TABLE_P(hash
)) {
3639 rb_gc_writebarrier_remember(values
);
3640 RARRAY_PTR_USE(values
, ptr
, {
3641 size
= ar_values(hash
, ptr
, size
);
3644 else if (RHASH_ST_TABLE_P(hash
)) {
3645 st_table
*table
= RHASH_ST_TABLE(hash
);
3646 rb_gc_writebarrier_remember(values
);
3647 RARRAY_PTR_USE(values
, ptr
, {
3648 size
= st_values(table
, ptr
, size
);
3651 rb_ary_set_len(values
, size
);
3655 rb_hash_foreach(hash
, values_i
, values
);
3663 * hash.include?(key) -> true or false
3664 * hash.has_key?(key) -> true or false
3665 * hash.key?(key) -> true or false
3666 * hash.member?(key) -> true or false
3668 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
3672 rb_hash_has_key(VALUE hash
, VALUE key
)
3674 return RBOOL(hash_stlike_lookup(hash
, key
, NULL
));
3678 rb_hash_search_value(VALUE key
, VALUE value
, VALUE arg
)
3680 VALUE
*data
= (VALUE
*)arg
;
3682 if (rb_equal(value
, data
[1])) {
3691 * hash.has_value?(value) -> true or false
3692 * hash.value?(value) -> true or false
3694 * Returns +true+ if +value+ is a value in +self+, otherwise +false+.
3698 rb_hash_has_value(VALUE hash
, VALUE val
)
3704 rb_hash_foreach(hash
, rb_hash_search_value
, (VALUE
)data
);
3715 eql_i(VALUE key
, VALUE val1
, VALUE arg
)
3717 struct equal_data
*data
= (struct equal_data
*)arg
;
3720 if (!hash_stlike_lookup(data
->hash
, key
, &val2
)) {
3721 data
->result
= Qfalse
;
3725 if (!(data
->eql
? rb_eql(val1
, (VALUE
)val2
) : (int)rb_equal(val1
, (VALUE
)val2
))) {
3726 data
->result
= Qfalse
;
3734 recursive_eql(VALUE hash
, VALUE dt
, int recur
)
3736 struct equal_data
*data
;
3738 if (recur
) return Qtrue
; /* Subtle! */
3739 data
= (struct equal_data
*)dt
;
3740 data
->result
= Qtrue
;
3741 rb_hash_foreach(hash
, eql_i
, dt
);
3743 return data
->result
;
3747 hash_equal(VALUE hash1
, VALUE hash2
, int eql
)
3749 struct equal_data data
;
3751 if (hash1
== hash2
) return Qtrue
;
3752 if (!RB_TYPE_P(hash2
, T_HASH
)) {
3753 if (!rb_respond_to(hash2
, idTo_hash
)) {
3757 if (rb_eql(hash2
, hash1
)) {
3765 return rb_equal(hash2
, hash1
);
3768 if (RHASH_SIZE(hash1
) != RHASH_SIZE(hash2
))
3770 if (!RHASH_TABLE_EMPTY_P(hash1
) && !RHASH_TABLE_EMPTY_P(hash2
)) {
3771 if (RHASH_TYPE(hash1
) != RHASH_TYPE(hash2
)) {
3777 return rb_exec_recursive_paired(recursive_eql
, hash1
, hash2
, (VALUE
)&data
);
3782 if (!(rb_equal(RHASH_IFNONE(hash1
), RHASH_IFNONE(hash2
)) &&
3783 FL_TEST(hash1
, RHASH_PROC_DEFAULT
) == FL_TEST(hash2
, RHASH_PROC_DEFAULT
)))
3791 * hash == object -> true or false
3793 * Returns +true+ if all of the following are true:
3794 * * +object+ is a +Hash+ object.
3795 * * +hash+ and +object+ have the same keys (regardless of order).
3796 * * For each key +key+, <tt>hash[key] == object[key]</tt>.
3798 * Otherwise, returns +false+.
3801 * h1 = {foo: 0, bar: 1, baz: 2}
3802 * h2 = {foo: 0, bar: 1, baz: 2}
3803 * h1 == h2 # => true
3804 * h3 = {baz: 2, bar: 1, foo: 0}
3805 * h1 == h3 # => true
3809 rb_hash_equal(VALUE hash1
, VALUE hash2
)
3811 return hash_equal(hash1
, hash2
, FALSE
);
3816 * hash.eql?(object) -> true or false
3818 * Returns +true+ if all of the following are true:
3819 * * +object+ is a +Hash+ object.
3820 * * +hash+ and +object+ have the same keys (regardless of order).
3821 * * For each key +key+, <tt>h[key].eql?(object[key])</tt>.
3823 * Otherwise, returns +false+.
3825 * h1 = {foo: 0, bar: 1, baz: 2}
3826 * h2 = {foo: 0, bar: 1, baz: 2}
3827 * h1.eql? h2 # => true
3828 * h3 = {baz: 2, bar: 1, foo: 0}
3829 * h1.eql? h3 # => true
3833 rb_hash_eql(VALUE hash1
, VALUE hash2
)
3835 return hash_equal(hash1
, hash2
, TRUE
);
3839 hash_i(VALUE key
, VALUE val
, VALUE arg
)
3841 st_index_t
*hval
= (st_index_t
*)arg
;
3842 st_index_t hdata
[2];
3844 hdata
[0] = rb_hash(key
);
3845 hdata
[1] = rb_hash(val
);
3846 *hval
^= st_hash(hdata
, sizeof(hdata
), 0);
3852 * hash.hash -> an_integer
3854 * Returns the Integer hash-code for the hash.
3856 * Two +Hash+ objects have the same hash-code if their content is the same
3857 * (regardless of order):
3858 * h1 = {foo: 0, bar: 1, baz: 2}
3859 * h2 = {baz: 2, bar: 1, foo: 0}
3860 * h2.hash == h1.hash # => true
3861 * h2.eql? h1 # => true
3865 rb_hash_hash(VALUE hash
)
3867 st_index_t size
= RHASH_SIZE(hash
);
3868 st_index_t hval
= rb_hash_start(size
);
3869 hval
= rb_hash_uint(hval
, (st_index_t
)rb_hash_hash
);
3871 rb_hash_foreach(hash
, hash_i
, (VALUE
)&hval
);
3873 hval
= rb_hash_end(hval
);
3874 return ST2FIX(hval
);
3878 rb_hash_invert_i(VALUE key
, VALUE value
, VALUE hash
)
3880 rb_hash_aset(hash
, value
, key
);
3886 * hash.invert -> new_hash
3888 * Returns a new +Hash+ object with the each key-value pair inverted:
3889 * h = {foo: 0, bar: 1, baz: 2}
3891 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3893 * Overwrites any repeated new keys:
3894 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
3895 * h = {foo: 0, bar: 0, baz: 0}
3896 * h.invert # => {0=>:baz}
3900 rb_hash_invert(VALUE hash
)
3902 VALUE h
= rb_hash_new_with_size(RHASH_SIZE(hash
));
3904 rb_hash_foreach(hash
, rb_hash_invert_i
, h
);
3909 rb_hash_update_i(VALUE key
, VALUE value
, VALUE hash
)
3911 rb_hash_aset(hash
, key
, value
);
3916 rb_hash_update_block_callback(st_data_t
*key
, st_data_t
*value
, struct update_arg
*arg
, int existing
)
3918 st_data_t newvalue
= arg
->arg
;
3921 newvalue
= (st_data_t
)rb_yield_values(3, (VALUE
)*key
, (VALUE
)*value
, (VALUE
)newvalue
);
3923 else if (RHASH_STRING_KEY_P(arg
->hash
, *key
) && !RB_OBJ_FROZEN(*key
)) {
3924 *key
= rb_hash_key_str(*key
);
3930 NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback
)
3933 rb_hash_update_block_i(VALUE key
, VALUE value
, VALUE hash
)
3935 RHASH_UPDATE(hash
, key
, rb_hash_update_block_callback
, value
);
3941 * hash.merge! -> self
3942 * hash.merge!(*other_hashes) -> self
3943 * hash.merge!(*other_hashes) { |key, old_value, new_value| ... } -> self
3945 * Merges each of +other_hashes+ into +self+; returns +self+.
3947 * Each argument in +other_hashes+ must be a +Hash+.
3949 * With arguments and no block:
3950 * * Returns +self+, after the given hashes are merged into it.
3951 * * The given hashes are merged left to right.
3952 * * Each new entry is added at the end.
3953 * * Each duplicate-key entry's value overwrites the previous value.
3956 * h = {foo: 0, bar: 1, baz: 2}
3957 * h1 = {bat: 3, bar: 4}
3958 * h2 = {bam: 5, bat:6}
3959 * h.merge!(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
3961 * With arguments and a block:
3962 * * Returns +self+, after the given hashes are merged.
3963 * * The given hashes are merged left to right.
3964 * * Each new-key entry is added at the end.
3965 * * For each duplicate key:
3966 * * Calls the block with the key and the old and new values.
3967 * * The block's return value becomes the new value for the entry.
3970 * h = {foo: 0, bar: 1, baz: 2}
3971 * h1 = {bat: 3, bar: 4}
3972 * h2 = {bam: 5, bat:6}
3973 * h3 = h.merge!(h1, h2) { |key, old_value, new_value| old_value + new_value }
3974 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
3976 * With no arguments:
3977 * * Returns +self+, unmodified.
3978 * * The block, if given, is ignored.
3981 * h = {foo: 0, bar: 1, baz: 2}
3982 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
3983 * h1 = h.merge! { |key, old_value, new_value| raise 'Cannot happen' }
3984 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3988 rb_hash_update(int argc
, VALUE
*argv
, VALUE self
)
3991 bool block_given
= rb_block_given_p();
3993 rb_hash_modify(self
);
3994 for (i
= 0; i
< argc
; i
++){
3995 VALUE hash
= to_hash(argv
[i
]);
3997 rb_hash_foreach(hash
, rb_hash_update_block_i
, self
);
4000 rb_hash_foreach(hash
, rb_hash_update_i
, self
);
4006 struct update_func_arg
{
4009 rb_hash_update_func
*func
;
4013 rb_hash_update_func_callback(st_data_t
*key
, st_data_t
*value
, struct update_arg
*arg
, int existing
)
4015 struct update_func_arg
*uf_arg
= (struct update_func_arg
*)arg
->arg
;
4016 VALUE newvalue
= uf_arg
->value
;
4019 newvalue
= (*uf_arg
->func
)((VALUE
)*key
, (VALUE
)*value
, newvalue
);
4025 NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback
)
4028 rb_hash_update_func_i(VALUE key
, VALUE value
, VALUE arg0
)
4030 struct update_func_arg
*arg
= (struct update_func_arg
*)arg0
;
4031 VALUE hash
= arg
->hash
;
4034 RHASH_UPDATE(hash
, key
, rb_hash_update_func_callback
, (VALUE
)arg
);
4039 rb_hash_update_by(VALUE hash1
, VALUE hash2
, rb_hash_update_func
*func
)
4041 rb_hash_modify(hash1
);
4042 hash2
= to_hash(hash2
);
4044 struct update_func_arg arg
;
4047 rb_hash_foreach(hash2
, rb_hash_update_func_i
, (VALUE
)&arg
);
4050 rb_hash_foreach(hash2
, rb_hash_update_i
, hash1
);
4057 * hash.merge -> copy_of_self
4058 * hash.merge(*other_hashes) -> new_hash
4059 * hash.merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4061 * Returns the new +Hash+ formed by merging each of +other_hashes+
4062 * into a copy of +self+.
4064 * Each argument in +other_hashes+ must be a +Hash+.
4068 * With arguments and no block:
4069 * * Returns the new +Hash+ object formed by merging each successive
4070 * +Hash+ in +other_hashes+ into +self+.
4071 * * Each new-key entry is added at the end.
4072 * * Each duplicate-key entry's value overwrites the previous value.
4075 * h = {foo: 0, bar: 1, baz: 2}
4076 * h1 = {bat: 3, bar: 4}
4077 * h2 = {bam: 5, bat:6}
4078 * h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
4080 * With arguments and a block:
4081 * * Returns a new +Hash+ object that is the merge of +self+ and each given hash.
4082 * * The given hashes are merged left to right.
4083 * * Each new-key entry is added at the end.
4084 * * For each duplicate key:
4085 * * Calls the block with the key and the old and new values.
4086 * * The block's return value becomes the new value for the entry.
4089 * h = {foo: 0, bar: 1, baz: 2}
4090 * h1 = {bat: 3, bar: 4}
4091 * h2 = {bam: 5, bat:6}
4092 * h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4093 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4095 * With no arguments:
4096 * * Returns a copy of +self+.
4097 * * The block, if given, is ignored.
4100 * h = {foo: 0, bar: 1, baz: 2}
4101 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4102 * h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
4103 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4107 rb_hash_merge(int argc
, VALUE
*argv
, VALUE self
)
4109 return rb_hash_update(argc
, argv
, copy_compare_by_id(rb_hash_dup(self
), self
));
4113 assoc_cmp(VALUE a
, VALUE b
)
4115 return !RTEST(rb_equal(a
, b
));
4124 assoc_lookup(VALUE arg
)
4126 struct assoc_arg
*p
= (struct assoc_arg
*)arg
;
4128 if (st_lookup(p
->tbl
, p
->key
, &data
)) return (VALUE
)data
;
4133 assoc_i(VALUE key
, VALUE val
, VALUE arg
)
4135 VALUE
*args
= (VALUE
*)arg
;
4137 if (RTEST(rb_equal(args
[0], key
))) {
4138 args
[1] = rb_assoc_new(key
, val
);
4146 * hash.assoc(key) -> new_array or nil
4148 * If the given +key+ is found, returns a 2-element Array containing that key and its value:
4149 * h = {foo: 0, bar: 1, baz: 2}
4150 * h.assoc(:bar) # => [:bar, 1]
4152 * Returns +nil+ if key +key+ is not found.
4156 rb_hash_assoc(VALUE hash
, VALUE key
)
4160 if (RHASH_EMPTY_P(hash
)) return Qnil
;
4162 if (RHASH_ST_TABLE_P(hash
) && !RHASH_IDENTHASH_P(hash
)) {
4163 VALUE value
= Qundef
;
4164 st_table assoctable
= *RHASH_ST_TABLE(hash
);
4165 assoctable
.type
= &(struct st_hash_type
){
4166 .compare
= assoc_cmp
,
4167 .hash
= assoctable
.type
->hash
,
4169 VALUE arg
= (VALUE
)&(struct assoc_arg
){
4171 .key
= (st_data_t
)key
,
4174 if (RB_OBJ_FROZEN(hash
)) {
4175 value
= assoc_lookup(arg
);
4178 hash_iter_lev_inc(hash
);
4179 value
= rb_ensure(assoc_lookup
, arg
, hash_foreach_ensure
, hash
);
4182 if (!UNDEF_P(value
)) return rb_assoc_new(key
, value
);
4187 rb_hash_foreach(hash
, assoc_i
, (VALUE
)args
);
4192 rassoc_i(VALUE key
, VALUE val
, VALUE arg
)
4194 VALUE
*args
= (VALUE
*)arg
;
4196 if (RTEST(rb_equal(args
[0], val
))) {
4197 args
[1] = rb_assoc_new(key
, val
);
4205 * hash.rassoc(value) -> new_array or nil
4207 * Returns a new 2-element Array consisting of the key and value
4208 * of the first-found entry whose value is <tt>==</tt> to value
4209 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
4210 * h = {foo: 0, bar: 1, baz: 1}
4211 * h.rassoc(1) # => [:bar, 1]
4213 * Returns +nil+ if no such value found.
4217 rb_hash_rassoc(VALUE hash
, VALUE obj
)
4223 rb_hash_foreach(hash
, rassoc_i
, (VALUE
)args
);
4228 flatten_i(VALUE key
, VALUE val
, VALUE ary
)
4234 rb_ary_cat(ary
, pair
, 2);
4241 * hash.flatten -> new_array
4242 * hash.flatten(level) -> new_array
4244 * Returns a new Array object that is a 1-dimensional flattening of +self+.
4248 * By default, nested Arrays are not flattened:
4249 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4250 * h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
4252 * Takes the depth of recursive flattening from Integer argument +level+:
4253 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4254 * h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
4255 * h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
4256 * h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
4257 * h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
4259 * When +level+ is negative, flattens all nested Arrays:
4260 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4261 * h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
4262 * h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
4264 * When +level+ is zero, returns the equivalent of #to_a :
4265 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4266 * h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
4267 * h.flatten(0) == h.to_a # => true
4271 rb_hash_flatten(int argc
, VALUE
*argv
, VALUE hash
)
4275 rb_check_arity(argc
, 0, 1);
4278 int level
= NUM2INT(argv
[0]);
4280 if (level
== 0) return rb_hash_to_a(hash
);
4282 ary
= rb_ary_new_capa(RHASH_SIZE(hash
) * 2);
4283 rb_hash_foreach(hash
, flatten_i
, ary
);
4287 VALUE ary_flatten_level
= INT2FIX(level
);
4288 rb_funcallv(ary
, id_flatten_bang
, 1, &ary_flatten_level
);
4290 else if (level
< 0) {
4291 /* flatten recursively */
4292 rb_funcallv(ary
, id_flatten_bang
, 0, 0);
4296 ary
= rb_ary_new_capa(RHASH_SIZE(hash
) * 2);
4297 rb_hash_foreach(hash
, flatten_i
, ary
);
4304 delete_if_nil(VALUE key
, VALUE value
, VALUE hash
)
4314 * hash.compact -> new_hash
4316 * Returns a copy of +self+ with all +nil+-valued entries removed:
4317 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4319 * h1 # => {:foo=>0, :baz=>2}
4323 rb_hash_compact(VALUE hash
)
4325 VALUE result
= rb_hash_dup(hash
);
4326 if (!RHASH_EMPTY_P(hash
)) {
4327 rb_hash_foreach(result
, delete_if_nil
, result
);
4328 compact_after_delete(result
);
4330 else if (rb_hash_compare_by_id_p(hash
)) {
4331 result
= rb_hash_compare_by_id(result
);
4338 * hash.compact! -> self or nil
4340 * Returns +self+ with all its +nil+-valued entries removed (in place):
4341 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4342 * h.compact! # => {:foo=>0, :baz=>2}
4344 * Returns +nil+ if no entries were removed.
4348 rb_hash_compact_bang(VALUE hash
)
4351 rb_hash_modify_check(hash
);
4352 n
= RHASH_SIZE(hash
);
4354 rb_hash_foreach(hash
, delete_if_nil
, hash
);
4355 if (n
!= RHASH_SIZE(hash
))
4363 * hash.compare_by_identity -> self
4365 * Sets +self+ to consider only identity in comparing keys;
4366 * two keys are considered the same only if they are the same object;
4369 * By default, these two object are considered to be the same key,
4370 * so +s1+ will overwrite +s0+:
4374 * h.compare_by_identity? # => false
4379 * After calling \#compare_by_identity, the keys are considered to be different,
4380 * and therefore do not overwrite each other:
4382 * h.compare_by_identity # => {}
4383 * h.compare_by_identity? # => true
4386 * h # => {"x"=>0, "x"=>1}
4390 rb_hash_compare_by_id(VALUE hash
)
4393 st_table
*identtable
;
4395 if (rb_hash_compare_by_id_p(hash
)) return hash
;
4397 rb_hash_modify_check(hash
);
4398 if (hash_iterating_p(hash
)) {
4399 rb_raise(rb_eRuntimeError
, "compare_by_identity during iteration");
4402 if (RHASH_TABLE_EMPTY_P(hash
)) {
4403 // Fast path: There's nothing to rehash, so we don't need a `tmp` table.
4404 // We're most likely an AR table, so this will need an allocation.
4405 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
4406 HASH_ASSERT(RHASH_ST_TABLE_P(hash
));
4408 RHASH_ST_TABLE(hash
)->type
= &identhash
;
4411 // Slow path: Need to rehash the members of `self` into a new
4412 // `tmp` table using the new `identhash` compare/hash functions.
4413 tmp
= hash_alloc(0);
4414 hash_st_table_init(tmp
, &identhash
, RHASH_SIZE(hash
));
4415 identtable
= RHASH_ST_TABLE(tmp
);
4417 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
4420 // We know for sure `identtable` is an st table,
4421 // so we can skip `ar_force_convert_table` here.
4422 RHASH_ST_TABLE_SET(hash
, identtable
);
4423 RHASH_ST_CLEAR(tmp
);
4431 * hash.compare_by_identity? -> true or false
4433 * Returns +true+ if #compare_by_identity has been called, +false+ otherwise.
4437 rb_hash_compare_by_id_p(VALUE hash
)
4439 return RBOOL(RHASH_IDENTHASH_P(hash
));
4443 rb_ident_hash_new(void)
4445 VALUE hash
= rb_hash_new();
4446 hash_st_table_init(hash
, &identhash
, 0);
4451 rb_ident_hash_new_with_size(st_index_t size
)
4453 VALUE hash
= rb_hash_new();
4454 hash_st_table_init(hash
, &identhash
, size
);
4459 rb_init_identtable(void)
4461 return st_init_table(&identhash
);
4465 any_p_i(VALUE key
, VALUE value
, VALUE arg
)
4467 VALUE ret
= rb_yield(rb_assoc_new(key
, value
));
4469 *(VALUE
*)arg
= Qtrue
;
4476 any_p_i_fast(VALUE key
, VALUE value
, VALUE arg
)
4478 VALUE ret
= rb_yield_values(2, key
, value
);
4480 *(VALUE
*)arg
= Qtrue
;
4487 any_p_i_pattern(VALUE key
, VALUE value
, VALUE arg
)
4489 VALUE ret
= rb_funcall(((VALUE
*)arg
)[1], idEqq
, 1, rb_assoc_new(key
, value
));
4491 *(VALUE
*)arg
= Qtrue
;
4499 * hash.any? -> true or false
4500 * hash.any?(object) -> true or false
4501 * hash.any? {|key, value| ... } -> true or false
4503 * Returns +true+ if any element satisfies a given criterion;
4504 * +false+ otherwise.
4506 * If +self+ has no element, returns +false+ and argument or block
4509 * With no argument and no block,
4510 * returns +true+ if +self+ is non-empty; +false+ if empty.
4512 * With argument +object+ and no block,
4513 * returns +true+ if for any key +key+
4514 * <tt>h.assoc(key) == object</tt>:
4515 * h = {foo: 0, bar: 1, baz: 2}
4516 * h.any?([:bar, 1]) # => true
4517 * h.any?([:bar, 0]) # => false
4518 * h.any?([:baz, 1]) # => false
4520 * With no argument and a block,
4521 * calls the block with each key-value pair;
4522 * returns +true+ if the block returns any truthy value,
4523 * +false+ otherwise:
4524 * h = {foo: 0, bar: 1, baz: 2}
4525 * h.any? {|key, value| value < 3 } # => true
4526 * h.any? {|key, value| value > 3 } # => false
4528 * Related: Enumerable#any?
4532 rb_hash_any_p(int argc
, VALUE
*argv
, VALUE hash
)
4537 rb_check_arity(argc
, 0, 1);
4538 if (RHASH_EMPTY_P(hash
)) return Qfalse
;
4540 if (rb_block_given_p()) {
4541 rb_warn("given block not used");
4545 rb_hash_foreach(hash
, any_p_i_pattern
, (VALUE
)args
);
4548 if (!rb_block_given_p()) {
4549 /* yields pairs, never false */
4552 if (rb_block_pair_yield_optimizable())
4553 rb_hash_foreach(hash
, any_p_i_fast
, (VALUE
)args
);
4555 rb_hash_foreach(hash
, any_p_i
, (VALUE
)args
);
4562 * hash.dig(key, *identifiers) -> object
4564 * Finds and returns the object in nested objects
4565 * that is specified by +key+ and +identifiers+.
4566 * The nested objects may be instances of various classes.
4567 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4570 * h = {foo: {bar: {baz: 2}}}
4571 * h.dig(:foo) # => {:bar=>{:baz=>2}}
4572 * h.dig(:foo, :bar) # => {:baz=>2}
4573 * h.dig(:foo, :bar, :baz) # => 2
4574 * h.dig(:foo, :bar, :BAZ) # => nil
4576 * Nested Hashes and Arrays:
4577 * h = {foo: {bar: [:a, :b, :c]}}
4578 * h.dig(:foo, :bar, 2) # => :c
4580 * This method will use the {default values}[rdoc-ref:Hash@Default+Values]
4581 * for keys that are not present:
4582 * h = {foo: {bar: [:a, :b, :c]}}
4583 * h.dig(:hello) # => nil
4584 * h.default_proc = -> (hash, _key) { hash }
4585 * h.dig(:hello, :world) # => h
4586 * h.dig(:hello, :world, :foo, :bar, 2) # => :c
4590 rb_hash_dig(int argc
, VALUE
*argv
, VALUE self
)
4592 rb_check_arity(argc
, 1, UNLIMITED_ARGUMENTS
);
4593 self
= rb_hash_aref(self
, *argv
);
4594 if (!--argc
) return self
;
4596 return rb_obj_dig(argc
, argv
, self
, Qnil
);
4600 hash_le_i(VALUE key
, VALUE value
, VALUE arg
)
4602 VALUE
*args
= (VALUE
*)arg
;
4603 VALUE v
= rb_hash_lookup2(args
[0], key
, Qundef
);
4604 if (!UNDEF_P(v
) && rb_equal(value
, v
)) return ST_CONTINUE
;
4610 hash_le(VALUE hash1
, VALUE hash2
)
4615 rb_hash_foreach(hash1
, hash_le_i
, (VALUE
)args
);
4621 * hash <= other_hash -> true or false
4623 * Returns +true+ if +hash+ is a subset of +other_hash+, +false+ otherwise:
4624 * h1 = {foo: 0, bar: 1}
4625 * h2 = {foo: 0, bar: 1, baz: 2}
4626 * h1 <= h2 # => true
4627 * h2 <= h1 # => false
4628 * h1 <= h1 # => true
4631 rb_hash_le(VALUE hash
, VALUE other
)
4633 other
= to_hash(other
);
4634 if (RHASH_SIZE(hash
) > RHASH_SIZE(other
)) return Qfalse
;
4635 return hash_le(hash
, other
);
4640 * hash < other_hash -> true or false
4642 * Returns +true+ if +hash+ is a proper subset of +other_hash+, +false+ otherwise:
4643 * h1 = {foo: 0, bar: 1}
4644 * h2 = {foo: 0, bar: 1, baz: 2}
4646 * h2 < h1 # => false
4647 * h1 < h1 # => false
4650 rb_hash_lt(VALUE hash
, VALUE other
)
4652 other
= to_hash(other
);
4653 if (RHASH_SIZE(hash
) >= RHASH_SIZE(other
)) return Qfalse
;
4654 return hash_le(hash
, other
);
4659 * hash >= other_hash -> true or false
4661 * Returns +true+ if +hash+ is a superset of +other_hash+, +false+ otherwise:
4662 * h1 = {foo: 0, bar: 1, baz: 2}
4663 * h2 = {foo: 0, bar: 1}
4664 * h1 >= h2 # => true
4665 * h2 >= h1 # => false
4666 * h1 >= h1 # => true
4669 rb_hash_ge(VALUE hash
, VALUE other
)
4671 other
= to_hash(other
);
4672 if (RHASH_SIZE(hash
) < RHASH_SIZE(other
)) return Qfalse
;
4673 return hash_le(other
, hash
);
4678 * hash > other_hash -> true or false
4680 * Returns +true+ if +hash+ is a proper superset of +other_hash+, +false+ otherwise:
4681 * h1 = {foo: 0, bar: 1, baz: 2}
4682 * h2 = {foo: 0, bar: 1}
4684 * h2 > h1 # => false
4685 * h1 > h1 # => false
4688 rb_hash_gt(VALUE hash
, VALUE other
)
4690 other
= to_hash(other
);
4691 if (RHASH_SIZE(hash
) <= RHASH_SIZE(other
)) return Qfalse
;
4692 return hash_le(other
, hash
);
4696 hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key
, hash
))
4698 rb_check_arity(argc
, 1, 1);
4699 return rb_hash_aref(hash
, *argv
);
4704 * hash.to_proc -> proc
4706 * Returns a Proc object that maps a key to its value:
4707 * h = {foo: 0, bar: 1, baz: 2}
4709 * proc.class # => Proc
4710 * proc.call(:foo) # => 0
4711 * proc.call(:bar) # => 1
4712 * proc.call(:nosuch) # => nil
4715 rb_hash_to_proc(VALUE hash
)
4717 return rb_func_lambda_new(hash_proc_call
, hash
, 1, 1);
4722 rb_hash_deconstruct_keys(VALUE hash
, VALUE keys
)
4728 add_new_i(st_data_t
*key
, st_data_t
*val
, st_data_t arg
, int existing
)
4730 VALUE
*args
= (VALUE
*)arg
;
4731 if (existing
) return ST_STOP
;
4732 RB_OBJ_WRITTEN(args
[0], Qundef
, (VALUE
)*key
);
4733 RB_OBJ_WRITE(args
[0], (VALUE
*)val
, args
[1]);
4738 * add +key+ to +val+ pair if +hash+ does not contain +key+.
4739 * returns non-zero if +key+ was contained.
4742 rb_hash_add_new_element(VALUE hash
, VALUE key
, VALUE val
)
4750 if (RHASH_AR_TABLE_P(hash
)) {
4751 ret
= ar_update(hash
, (st_data_t
)key
, add_new_i
, (st_data_t
)args
);
4755 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
4758 tbl
= RHASH_TBL_RAW(hash
);
4759 return st_update(tbl
, (st_data_t
)key
, add_new_i
, (st_data_t
)args
);
4764 key_stringify(VALUE key
)
4766 return (rb_obj_class(key
) == rb_cString
&& !RB_OBJ_FROZEN(key
)) ?
4767 rb_hash_key_str(key
) : key
;
4771 ar_bulk_insert(VALUE hash
, long argc
, const VALUE
*argv
)
4774 for (i
= 0; i
< argc
; ) {
4775 st_data_t k
= key_stringify(argv
[i
++]);
4776 st_data_t v
= argv
[i
++];
4777 ar_insert(hash
, k
, v
);
4778 RB_OBJ_WRITTEN(hash
, Qundef
, k
);
4779 RB_OBJ_WRITTEN(hash
, Qundef
, v
);
4784 rb_hash_bulk_insert(long argc
, const VALUE
*argv
, VALUE hash
)
4786 HASH_ASSERT(argc
% 2 == 0);
4788 st_index_t size
= argc
/ 2;
4790 if (RHASH_AR_TABLE_P(hash
) &&
4791 (RHASH_AR_TABLE_SIZE(hash
) + size
<= RHASH_AR_TABLE_MAX_SIZE
)) {
4792 ar_bulk_insert(hash
, argc
, argv
);
4795 rb_hash_bulk_insert_into_st_table(argc
, argv
, hash
);
4800 static char **origenviron
;
4802 #define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
4803 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
4804 static char **my_environ
;
4806 #define environ my_environ
4808 #define getenv(n) rb_w32_ugetenv(n)
4809 #elif defined(__APPLE__)
4811 #define environ (*_NSGetEnviron())
4812 #define GET_ENVIRON(e) (e)
4813 #define FREE_ENVIRON(e)
4815 extern char **environ
;
4816 #define GET_ENVIRON(e) (e)
4817 #define FREE_ENVIRON(e)
4819 #ifdef ENV_IGNORECASE
4820 #define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
4821 #define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
4823 #define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
4824 #define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
4827 #define ENV_LOCK() RB_VM_LOCK_ENTER()
4828 #define ENV_UNLOCK() RB_VM_LOCK_LEAVE()
4830 static inline rb_encoding
*
4834 return rb_utf8_encoding();
4836 return rb_locale_encoding();
4841 env_enc_str_new(const char *ptr
, long len
, rb_encoding
*enc
)
4843 VALUE str
= rb_external_str_new_with_enc(ptr
, len
, enc
);
4850 env_str_new(const char *ptr
, long len
)
4852 return env_enc_str_new(ptr
, len
, env_encoding());
4856 env_str_new2(const char *ptr
)
4858 if (!ptr
) return Qnil
;
4859 return env_str_new(ptr
, strlen(ptr
));
4863 getenv_with_lock(const char *name
)
4868 const char *val
= getenv(name
);
4869 ret
= env_str_new2(val
);
4876 has_env_with_lock(const char *name
)
4886 return val
? true : false;
4889 static const char TZ_ENV
[] = "TZ";
4892 get_env_cstr(VALUE str
, const char *name
)
4895 rb_encoding
*enc
= rb_enc_get(str
);
4896 if (!rb_enc_asciicompat(enc
)) {
4897 rb_raise(rb_eArgError
, "bad environment variable %s: ASCII incompatible encoding: %s",
4898 name
, rb_enc_name(enc
));
4900 var
= RSTRING_PTR(str
);
4901 if (memchr(var
, '\0', RSTRING_LEN(str
))) {
4902 rb_raise(rb_eArgError
, "bad environment variable %s: contains null byte", name
);
4904 return rb_str_fill_terminator(str
, 1); /* ASCII compatible */
4907 #define get_env_ptr(var, val) \
4908 (var = get_env_cstr(val, #var))
4910 static inline const char *
4911 env_name(volatile VALUE
*s
)
4915 get_env_ptr(name
, *s
);
4919 #define env_name(s) env_name(&(s))
4921 static VALUE
env_aset(VALUE nm
, VALUE val
);
4924 reset_by_modified_env(const char *nam
)
4927 * ENV['TZ'] = nil has a special meaning.
4928 * TZ is no longer considered up-to-date and ruby call tzset() as needed.
4929 * It could be useful if sysadmin change /etc/localtime.
4930 * This hack might works only on Linux glibc.
4932 if (ENVMATCH(nam
, TZ_ENV
)) {
4933 ruby_reset_timezone();
4938 env_delete(VALUE name
)
4940 const char *nam
= env_name(name
);
4941 reset_by_modified_env(nam
);
4942 VALUE val
= getenv_with_lock(nam
);
4945 ruby_setenv(nam
, 0);
4952 * ENV.delete(name) -> value
4953 * ENV.delete(name) { |name| block } -> value
4954 * ENV.delete(missing_name) -> nil
4955 * ENV.delete(missing_name) { |name| block } -> block_value
4957 * Deletes the environment variable with +name+ if it exists and returns its value:
4959 * ENV.delete('foo') # => '0'
4961 * If a block is not given and the named environment variable does not exist, returns +nil+.
4963 * If a block given and the environment variable does not exist,
4964 * yields +name+ to the block and returns the value of the block:
4965 * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
4967 * If a block given and the environment variable exists,
4968 * deletes the environment variable and returns its value (ignoring the block):
4970 * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
4972 * Raises an exception if +name+ is invalid.
4973 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
4976 env_delete_m(VALUE obj
, VALUE name
)
4980 val
= env_delete(name
);
4981 if (NIL_P(val
) && rb_block_given_p()) val
= rb_yield(name
);
4987 * ENV[name] -> value
4989 * Returns the value for the environment variable +name+ if it exists:
4991 * ENV['foo'] # => "0"
4992 * Returns +nil+ if the named variable does not exist.
4994 * Raises an exception if +name+ is invalid.
4995 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
4998 rb_f_getenv(VALUE obj
, VALUE name
)
5000 const char *nam
= env_name(name
);
5001 VALUE env
= getenv_with_lock(nam
);
5007 * ENV.fetch(name) -> value
5008 * ENV.fetch(name, default) -> value
5009 * ENV.fetch(name) { |name| block } -> value
5011 * If +name+ is the name of an environment variable, returns its value:
5013 * ENV.fetch('foo') # => '0'
5014 * Otherwise if a block is given (but not a default value),
5015 * yields +name+ to the block and returns the block's return value:
5016 * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
5017 * Otherwise if a default value is given (but not a block), returns the default value:
5019 * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
5020 * If the environment variable does not exist and both default and block are given,
5021 * issues a warning ("warning: block supersedes default value argument"),
5022 * yields +name+ to the block, and returns the block's return value:
5023 * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
5024 * Raises KeyError if +name+ is valid, but not found,
5025 * and neither default value nor block is given:
5026 * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
5027 * Raises an exception if +name+ is invalid.
5028 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5031 env_fetch(int argc
, VALUE
*argv
, VALUE _
)
5038 rb_check_arity(argc
, 1, 2);
5040 block_given
= rb_block_given_p();
5041 if (block_given
&& argc
== 2) {
5042 rb_warn("block supersedes default value argument");
5044 nam
= env_name(key
);
5045 env
= getenv_with_lock(nam
);
5048 if (block_given
) return rb_yield(key
);
5050 rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE
"\"", key
), envtbl
, key
);
5057 #if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
5060 in_origenv(const char *str
)
5063 for (env
= origenviron
; *env
; ++env
) {
5064 if (*env
== str
) return 1;
5070 envix(const char *nam
)
5074 register int i
, len
= strlen(nam
);
5077 env
= GET_ENVIRON(environ
);
5078 for (i
= 0; env
[i
]; i
++) {
5079 if (ENVNMATCH(env
[i
],nam
,len
) && env
[i
][len
] == '=')
5080 break; /* memcmp must come first to avoid */
5081 } /* potential SEGV's */
5082 FREE_ENVIRON(environ
);
5089 getenvsize(const WCHAR
* p
)
5091 const WCHAR
* porg
= p
;
5092 while (*p
++) p
+= lstrlenW(p
) + 1;
5093 return p
- porg
+ 1;
5097 getenvblocksize(void)
5107 check_envsize(size_t n
)
5109 if (_WIN32_WINNT
< 0x0600 && rb_w32_osver() < 6) {
5110 /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */
5111 /* Windows Server 2003 and Windows XP: The maximum size of the
5112 * environment block for the process is 32,767 characters. */
5113 WCHAR
* p
= GetEnvironmentStringsW();
5114 if (!p
) return -1; /* never happen */
5116 FreeEnvironmentStringsW(p
);
5117 if (n
>= getenvblocksize()) {
5125 #if defined(_WIN32) || \
5126 (defined(__sun) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV)))
5128 NORETURN(static void invalid_envname(const char *name
));
5131 invalid_envname(const char *name
)
5133 rb_syserr_fail_str(EINVAL
, rb_sprintf("ruby_setenv(%s)", name
));
5137 check_envname(const char *name
)
5139 if (strchr(name
, '=')) {
5140 invalid_envname(name
);
5147 ruby_setenv(const char *name
, const char *value
)
5150 # if defined(MINGW_HAS_SECURE_API) || RUBY_MSVCRT_VERSION >= 80
5151 # define HAVE__WPUTENV_S 1
5158 check_envname(name
);
5159 len
= MultiByteToWideChar(CP_UTF8
, 0, name
, -1, NULL
, 0);
5162 len2
= MultiByteToWideChar(CP_UTF8
, 0, value
, -1, NULL
, 0);
5163 if (check_envsize((size_t)len
+ len2
)) { /* len and len2 include '\0' */
5164 goto fail
; /* 2 for '=' & '\0' */
5166 wname
= ALLOCV_N(WCHAR
, buf
, len
+ len2
);
5167 wvalue
= wname
+ len
;
5168 MultiByteToWideChar(CP_UTF8
, 0, name
, -1, wname
, len
);
5169 MultiByteToWideChar(CP_UTF8
, 0, value
, -1, wvalue
, len2
);
5170 #ifndef HAVE__WPUTENV_S
5171 wname
[len
-1] = L
'=';
5175 wname
= ALLOCV_N(WCHAR
, buf
, len
+ 1);
5176 MultiByteToWideChar(CP_UTF8
, 0, name
, -1, wname
, len
);
5177 wvalue
= wname
+ len
;
5179 #ifndef HAVE__WPUTENV_S
5180 wname
[len
-1] = L
'=';
5186 #ifndef HAVE__WPUTENV_S
5187 failed
= _wputenv(wname
);
5189 failed
= _wputenv_s(wname
, wvalue
);
5195 /* even if putenv() failed, clean up and try to delete the
5196 * variable from the system area. */
5197 if (!value
|| !*value
) {
5198 /* putenv() doesn't handle empty value */
5199 if (!SetEnvironmentVariable(name
, value
) &&
5200 GetLastError() != ERROR_ENVVAR_NOT_FOUND
) goto fail
;
5204 invalid_envname(name
);
5206 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
5211 ret
= setenv(name
, value
, 1);
5215 if (ret
) rb_sys_fail_sprintf("setenv(%s)", name
);
5218 #ifdef VOID_UNSETENV
5228 ret
= unsetenv(name
);
5232 if (ret
) rb_sys_fail_sprintf("unsetenv(%s)", name
);
5236 /* Solaris 9 (or earlier) does not have setenv(3C) and unsetenv(3C). */
5237 /* The below code was tested on Solaris 10 by:
5238 % ./configure ac_cv_func_setenv=no ac_cv_func_unsetenv=no
5240 size_t len
, mem_size
;
5241 char **env_ptr
, *str
, *mem_ptr
;
5243 check_envname(name
);
5246 mem_size
= len
+ strlen(value
) + 2;
5247 mem_ptr
= malloc(mem_size
);
5248 if (mem_ptr
== NULL
)
5249 rb_sys_fail_sprintf("malloc(%"PRIuSIZE
")", mem_size
);
5250 snprintf(mem_ptr
, mem_size
, "%s=%s", name
, value
);
5255 for (env_ptr
= GET_ENVIRON(environ
); (str
= *env_ptr
) != 0; ++env_ptr
) {
5256 if (!strncmp(str
, name
, len
) && str
[len
] == '=') {
5257 if (!in_origenv(str
)) free(str
);
5258 while ((env_ptr
[0] = env_ptr
[1]) != 0) env_ptr
++;
5269 ret
= putenv(mem_ptr
);
5275 rb_sys_fail_sprintf("putenv(%s)", name
);
5284 i
= envix(name
); /* where does it go? */
5286 if (environ
== origenviron
) { /* need we copy environment? */
5291 for (max
= i
; environ
[max
]; max
++) ;
5292 tmpenv
= ALLOC_N(char*, max
+2);
5293 for (j
=0; j
<max
; j
++) /* copy environment */
5294 tmpenv
[j
] = ruby_strdup(environ
[j
]);
5296 environ
= tmpenv
; /* tell exec where it is now */
5300 char **envp
= origenviron
;
5301 while (*envp
&& *envp
!= environ
[i
]) envp
++;
5305 while (environ
[i
]) {
5306 environ
[i
] = environ
[i
+1];
5312 else { /* does not exist yet */
5313 if (!value
) goto finish
;
5314 REALLOC_N(environ
, char*, i
+2); /* just expand it a bit */
5315 environ
[i
+1] = 0; /* make sure it's null terminated */
5318 len
= strlen(name
) + strlen(value
) + 2;
5319 environ
[i
] = ALLOC_N(char, len
);
5320 snprintf(environ
[i
],len
,"%s=%s",name
,value
); /* all that work just for this */
5329 ruby_unsetenv(const char *name
)
5331 ruby_setenv(name
, 0);
5336 * ENV[name] = value -> value
5337 * ENV.store(name, value) -> value
5339 * Creates, updates, or deletes the named environment variable, returning the value.
5340 * Both +name+ and +value+ may be instances of String.
5341 * See {Valid Names and Values}[rdoc-ref:ENV@Valid+Names+and+Values].
5343 * - If the named environment variable does not exist:
5344 * - If +value+ is +nil+, does nothing.
5346 * ENV['foo'] = nil # => nil
5347 * ENV.include?('foo') # => false
5348 * ENV.store('bar', nil) # => nil
5349 * ENV.include?('bar') # => false
5350 * - If +value+ is not +nil+, creates the environment variable with +name+ and +value+:
5351 * # Create 'foo' using ENV.[]=.
5352 * ENV['foo'] = '0' # => '0'
5353 * ENV['foo'] # => '0'
5354 * # Create 'bar' using ENV.store.
5355 * ENV.store('bar', '1') # => '1'
5356 * ENV['bar'] # => '1'
5357 * - If the named environment variable exists:
5358 * - If +value+ is not +nil+, updates the environment variable with value +value+:
5359 * # Update 'foo' using ENV.[]=.
5360 * ENV['foo'] = '2' # => '2'
5361 * ENV['foo'] # => '2'
5362 * # Update 'bar' using ENV.store.
5363 * ENV.store('bar', '3') # => '3'
5364 * ENV['bar'] # => '3'
5365 * - If +value+ is +nil+, deletes the environment variable:
5366 * # Delete 'foo' using ENV.[]=.
5367 * ENV['foo'] = nil # => nil
5368 * ENV.include?('foo') # => false
5369 * # Delete 'bar' using ENV.store.
5370 * ENV.store('bar', nil) # => nil
5371 * ENV.include?('bar') # => false
5373 * Raises an exception if +name+ or +value+ is invalid.
5374 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5377 env_aset_m(VALUE obj
, VALUE nm
, VALUE val
)
5379 return env_aset(nm
, val
);
5383 env_aset(VALUE nm
, VALUE val
)
5393 /* nm can be modified in `val.to_str`, don't get `name` before
5394 * check for `val` */
5395 get_env_ptr(name
, nm
);
5396 get_env_ptr(value
, val
);
5398 ruby_setenv(name
, value
);
5399 reset_by_modified_env(name
);
5406 rb_encoding
*enc
= raw
? 0 : rb_locale_encoding();
5407 VALUE ary
= rb_ary_new();
5411 char **env
= GET_ENVIRON(environ
);
5413 char *s
= strchr(*env
, '=');
5415 const char *p
= *env
;
5417 VALUE e
= raw
? rb_utf8_str_new(p
, l
) : env_enc_str_new(p
, l
, enc
);
5418 rb_ary_push(ary
, e
);
5422 FREE_ENVIRON(environ
);
5431 * ENV.keys -> array of names
5433 * Returns all variable names in an Array:
5434 * ENV.replace('foo' => '0', 'bar' => '1')
5435 * ENV.keys # => ['bar', 'foo']
5436 * The order of the names is OS-dependent.
5437 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5439 * Returns the empty Array if ENV is empty.
5445 return env_keys(FALSE
);
5449 rb_env_size(VALUE ehash
, VALUE args
, VALUE eobj
)
5456 env
= GET_ENVIRON(environ
);
5457 for (; *env
; ++env
) {
5458 if (strchr(*env
, '=')) {
5462 FREE_ENVIRON(environ
);
5466 return LONG2FIX(cnt
);
5471 * ENV.each_key { |name| block } -> ENV
5472 * ENV.each_key -> an_enumerator
5474 * Yields each environment variable name:
5475 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5477 * ENV.each_key { |name| names.push(name) } # => ENV
5478 * names # => ["bar", "foo"]
5480 * Returns an Enumerator if no block given:
5481 * e = ENV.each_key # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_key>
5483 * e.each { |name| names.push(name) } # => ENV
5484 * names # => ["bar", "foo"]
5487 env_each_key(VALUE ehash
)
5492 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5493 keys
= env_keys(FALSE
);
5494 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5495 rb_yield(RARRAY_AREF(keys
, i
));
5503 VALUE ary
= rb_ary_new();
5507 char **env
= GET_ENVIRON(environ
);
5510 char *s
= strchr(*env
, '=');
5512 rb_ary_push(ary
, env_str_new2(s
+1));
5516 FREE_ENVIRON(environ
);
5525 * ENV.values -> array of values
5527 * Returns all environment variable values in an Array:
5528 * ENV.replace('foo' => '0', 'bar' => '1')
5529 * ENV.values # => ['1', '0']
5530 * The order of the values is OS-dependent.
5531 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5533 * Returns the empty Array if ENV is empty.
5536 env_f_values(VALUE _
)
5538 return env_values();
5543 * ENV.each_value { |value| block } -> ENV
5544 * ENV.each_value -> an_enumerator
5546 * Yields each environment variable value:
5547 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5549 * ENV.each_value { |value| values.push(value) } # => ENV
5550 * values # => ["1", "0"]
5552 * Returns an Enumerator if no block given:
5553 * e = ENV.each_value # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_value>
5555 * e.each { |value| values.push(value) } # => ENV
5556 * values # => ["1", "0"]
5559 env_each_value(VALUE ehash
)
5564 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5565 values
= env_values();
5566 for (i
=0; i
<RARRAY_LEN(values
); i
++) {
5567 rb_yield(RARRAY_AREF(values
, i
));
5574 * ENV.each { |name, value| block } -> ENV
5575 * ENV.each -> an_enumerator
5576 * ENV.each_pair { |name, value| block } -> ENV
5577 * ENV.each_pair -> an_enumerator
5579 * Yields each environment variable name and its value as a 2-element Array:
5581 * ENV.each_pair { |name, value| h[name] = value } # => ENV
5582 * h # => {"bar"=>"1", "foo"=>"0"}
5584 * Returns an Enumerator if no block given:
5586 * e = ENV.each_pair # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_pair>
5587 * e.each { |name, value| h[name] = value } # => ENV
5588 * h # => {"bar"=>"1", "foo"=>"0"}
5591 env_each_pair(VALUE ehash
)
5595 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5597 VALUE ary
= rb_ary_new();
5601 char **env
= GET_ENVIRON(environ
);
5604 char *s
= strchr(*env
, '=');
5606 rb_ary_push(ary
, env_str_new(*env
, s
-*env
));
5607 rb_ary_push(ary
, env_str_new2(s
+1));
5611 FREE_ENVIRON(environ
);
5615 if (rb_block_pair_yield_optimizable()) {
5616 for (i
=0; i
<RARRAY_LEN(ary
); i
+=2) {
5617 rb_yield_values(2, RARRAY_AREF(ary
, i
), RARRAY_AREF(ary
, i
+1));
5621 for (i
=0; i
<RARRAY_LEN(ary
); i
+=2) {
5622 rb_yield(rb_assoc_new(RARRAY_AREF(ary
, i
), RARRAY_AREF(ary
, i
+1)));
5631 * ENV.reject! { |name, value| block } -> ENV or nil
5632 * ENV.reject! -> an_enumerator
5634 * Similar to ENV.delete_if, but returns +nil+ if no changes were made.
5636 * Yields each environment variable name and its value as a 2-element Array,
5637 * deleting each environment variable for which the block returns a truthy value,
5638 * and returning ENV (if any deletions) or +nil+ (if not):
5639 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5640 * ENV.reject! { |name, value| name.start_with?('b') } # => ENV
5641 * ENV # => {"foo"=>"0"}
5642 * ENV.reject! { |name, value| name.start_with?('b') } # => nil
5644 * Returns an Enumerator if no block given:
5645 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5646 * e = ENV.reject! # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:reject!>
5647 * e.each { |name, value| name.start_with?('b') } # => ENV
5648 * ENV # => {"foo"=>"0"}
5649 * e.each { |name, value| name.start_with?('b') } # => nil
5652 env_reject_bang(VALUE ehash
)
5658 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5659 keys
= env_keys(FALSE
);
5660 RBASIC_CLEAR_CLASS(keys
);
5661 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5662 VALUE val
= rb_f_getenv(Qnil
, RARRAY_AREF(keys
, i
));
5664 if (RTEST(rb_yield_values(2, RARRAY_AREF(keys
, i
), val
))) {
5665 env_delete(RARRAY_AREF(keys
, i
));
5671 if (del
== 0) return Qnil
;
5677 * ENV.delete_if { |name, value| block } -> ENV
5678 * ENV.delete_if -> an_enumerator
5680 * Yields each environment variable name and its value as a 2-element Array,
5681 * deleting each environment variable for which the block returns a truthy value,
5682 * and returning ENV (regardless of whether any deletions):
5683 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5684 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5685 * ENV # => {"foo"=>"0"}
5686 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5688 * Returns an Enumerator if no block given:
5689 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5690 * e = ENV.delete_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:delete_if!>
5691 * e.each { |name, value| name.start_with?('b') } # => ENV
5692 * ENV # => {"foo"=>"0"}
5693 * e.each { |name, value| name.start_with?('b') } # => ENV
5696 env_delete_if(VALUE ehash
)
5698 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5699 env_reject_bang(ehash
);
5705 * ENV.values_at(*names) -> array of values
5707 * Returns an Array containing the environment variable values associated with
5709 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5710 * ENV.values_at('foo', 'baz') # => ["0", "2"]
5712 * Returns +nil+ in the Array for each name that is not an ENV name:
5713 * ENV.values_at('foo', 'bat', 'bar', 'bam') # => ["0", nil, "1", nil]
5715 * Returns an empty Array if no names given.
5717 * Raises an exception if any name is invalid.
5718 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5721 env_values_at(int argc
, VALUE
*argv
, VALUE _
)
5726 result
= rb_ary_new();
5727 for (i
=0; i
<argc
; i
++) {
5728 rb_ary_push(result
, rb_f_getenv(Qnil
, argv
[i
]));
5735 * ENV.select { |name, value| block } -> hash of name/value pairs
5736 * ENV.select -> an_enumerator
5737 * ENV.filter { |name, value| block } -> hash of name/value pairs
5738 * ENV.filter -> an_enumerator
5740 * Yields each environment variable name and its value as a 2-element Array,
5741 * returning a Hash of the names and values for which the block returns a truthy value:
5742 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5743 * ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5744 * ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5746 * Returns an Enumerator if no block given:
5747 * e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select>
5748 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5749 * e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter>
5750 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5753 env_select(VALUE ehash
)
5759 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5760 result
= rb_hash_new();
5761 keys
= env_keys(FALSE
);
5762 for (i
= 0; i
< RARRAY_LEN(keys
); ++i
) {
5763 VALUE key
= RARRAY_AREF(keys
, i
);
5764 VALUE val
= rb_f_getenv(Qnil
, key
);
5766 if (RTEST(rb_yield_values(2, key
, val
))) {
5767 rb_hash_aset(result
, key
, val
);
5778 * ENV.select! { |name, value| block } -> ENV or nil
5779 * ENV.select! -> an_enumerator
5780 * ENV.filter! { |name, value| block } -> ENV or nil
5781 * ENV.filter! -> an_enumerator
5783 * Yields each environment variable name and its value as a 2-element Array,
5784 * deleting each entry for which the block returns +false+ or +nil+,
5785 * and returning ENV if any deletions made, or +nil+ otherwise:
5787 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5788 * ENV.select! { |name, value| name.start_with?('b') } # => ENV
5789 * ENV # => {"bar"=>"1", "baz"=>"2"}
5790 * ENV.select! { |name, value| true } # => nil
5792 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5793 * ENV.filter! { |name, value| name.start_with?('b') } # => ENV
5794 * ENV # => {"bar"=>"1", "baz"=>"2"}
5795 * ENV.filter! { |name, value| true } # => nil
5797 * Returns an Enumerator if no block given:
5799 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5800 * e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!>
5801 * e.each { |name, value| name.start_with?('b') } # => ENV
5802 * ENV # => {"bar"=>"1", "baz"=>"2"}
5803 * e.each { |name, value| true } # => nil
5805 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5806 * e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!>
5807 * e.each { |name, value| name.start_with?('b') } # => ENV
5808 * ENV # => {"bar"=>"1", "baz"=>"2"}
5809 * e.each { |name, value| true } # => nil
5812 env_select_bang(VALUE ehash
)
5818 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5819 keys
= env_keys(FALSE
);
5820 RBASIC_CLEAR_CLASS(keys
);
5821 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5822 VALUE val
= rb_f_getenv(Qnil
, RARRAY_AREF(keys
, i
));
5824 if (!RTEST(rb_yield_values(2, RARRAY_AREF(keys
, i
), val
))) {
5825 env_delete(RARRAY_AREF(keys
, i
));
5831 if (del
== 0) return Qnil
;
5837 * ENV.keep_if { |name, value| block } -> ENV
5838 * ENV.keep_if -> an_enumerator
5840 * Yields each environment variable name and its value as a 2-element Array,
5841 * deleting each environment variable for which the block returns +false+ or +nil+,
5842 * and returning ENV:
5843 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5844 * ENV.keep_if { |name, value| name.start_with?('b') } # => ENV
5845 * ENV # => {"bar"=>"1", "baz"=>"2"}
5847 * Returns an Enumerator if no block given:
5848 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5849 * e = ENV.keep_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:keep_if>
5850 * e.each { |name, value| name.start_with?('b') } # => ENV
5851 * ENV # => {"bar"=>"1", "baz"=>"2"}
5854 env_keep_if(VALUE ehash
)
5856 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5857 env_select_bang(ehash
);
5863 * ENV.slice(*names) -> hash of name/value pairs
5865 * Returns a Hash of the given ENV names and their corresponding values:
5866 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2', 'bat' => '3')
5867 * ENV.slice('foo', 'baz') # => {"foo"=>"0", "baz"=>"2"}
5868 * ENV.slice('baz', 'foo') # => {"baz"=>"2", "foo"=>"0"}
5869 * Raises an exception if any of the +names+ is invalid
5870 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
5871 * ENV.slice('foo', 'bar', :bat) # Raises TypeError (no implicit conversion of Symbol into String)
5874 env_slice(int argc
, VALUE
*argv
, VALUE _
)
5877 VALUE key
, value
, result
;
5880 return rb_hash_new();
5882 result
= rb_hash_new_with_size(argc
);
5884 for (i
= 0; i
< argc
; i
++) {
5886 value
= rb_f_getenv(Qnil
, key
);
5888 rb_hash_aset(result
, key
, value
);
5900 keys
= env_keys(TRUE
);
5901 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5902 VALUE key
= RARRAY_AREF(keys
, i
);
5903 const char *nam
= RSTRING_PTR(key
);
5904 ruby_setenv(nam
, 0);
5914 * Removes every environment variable; returns ENV:
5915 * ENV.replace('foo' => '0', 'bar' => '1')
5917 * ENV.clear # => ENV
5923 return rb_env_clear();
5930 * Returns String 'ENV':
5931 * ENV.to_s # => "ENV"
5936 return rb_usascii_str_new2("ENV");
5941 * ENV.inspect -> a_string
5943 * Returns the contents of the environment as a String:
5944 * ENV.replace('foo' => '0', 'bar' => '1')
5945 * ENV.inspect # => "{\"bar\"=>\"1\", \"foo\"=>\"0\"}"
5948 env_inspect(VALUE _
)
5951 VALUE str
= rb_str_buf_new2("{");
5955 char **env
= GET_ENVIRON(environ
);
5957 char *s
= strchr(*env
, '=');
5959 if (env
!= environ
) {
5960 rb_str_buf_cat2(str
, ", ");
5963 rb_str_buf_cat2(str
, "\"");
5964 rb_str_buf_cat(str
, *env
, s
-*env
);
5965 rb_str_buf_cat2(str
, "\"=>");
5966 i
= rb_inspect(rb_str_new2(s
+1));
5967 rb_str_buf_append(str
, i
);
5971 FREE_ENVIRON(environ
);
5975 rb_str_buf_cat2(str
, "}");
5982 * ENV.to_a -> array of 2-element arrays
5984 * Returns the contents of ENV as an Array of 2-element Arrays,
5985 * each of which is a name/value pair:
5986 * ENV.replace('foo' => '0', 'bar' => '1')
5987 * ENV.to_a # => [["bar", "1"], ["foo", "0"]]
5992 VALUE ary
= rb_ary_new();
5996 char **env
= GET_ENVIRON(environ
);
5998 char *s
= strchr(*env
, '=');
6000 rb_ary_push(ary
, rb_assoc_new(env_str_new(*env
, s
-*env
),
6001 env_str_new2(s
+1)));
6005 FREE_ENVIRON(environ
);
6016 * (Provided for compatibility with Hash.)
6018 * Does not modify ENV; returns +nil+.
6027 env_size_with_lock(void)
6033 char **env
= GET_ENVIRON(environ
);
6035 FREE_ENVIRON(environ
);
6044 * ENV.length -> an_integer
6045 * ENV.size -> an_integer
6047 * Returns the count of environment variables:
6048 * ENV.replace('foo' => '0', 'bar' => '1')
6055 return INT2FIX(env_size_with_lock());
6060 * ENV.empty? -> true or false
6062 * Returns +true+ when there are no environment variables, +false+ otherwise:
6064 * ENV.empty? # => true
6066 * ENV.empty? # => false
6069 env_empty_p(VALUE _
)
6075 char **env
= GET_ENVIRON(environ
);
6079 FREE_ENVIRON(environ
);
6083 return RBOOL(empty
);
6088 * ENV.include?(name) -> true or false
6089 * ENV.has_key?(name) -> true or false
6090 * ENV.member?(name) -> true or false
6091 * ENV.key?(name) -> true or false
6093 * Returns +true+ if there is an environment variable with the given +name+:
6094 * ENV.replace('foo' => '0', 'bar' => '1')
6095 * ENV.include?('foo') # => true
6096 * Returns +false+ if +name+ is a valid String and there is no such environment variable:
6097 * ENV.include?('baz') # => false
6098 * Returns +false+ if +name+ is the empty String or is a String containing character <code>'='</code>:
6099 * ENV.include?('') # => false
6100 * ENV.include?('=') # => false
6101 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6102 * ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6103 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6104 * ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6105 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6106 * Raises an exception if +name+ is not a String:
6107 * ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
6110 env_has_key(VALUE env
, VALUE key
)
6112 const char *s
= env_name(key
);
6113 return RBOOL(has_env_with_lock(s
));
6118 * ENV.assoc(name) -> [name, value] or nil
6120 * Returns a 2-element Array containing the name and value of the environment variable
6121 * for +name+ if it exists:
6122 * ENV.replace('foo' => '0', 'bar' => '1')
6123 * ENV.assoc('foo') # => ['foo', '0']
6124 * Returns +nil+ if +name+ is a valid String and there is no such environment variable.
6126 * Returns +nil+ if +name+ is the empty String or is a String containing character <code>'='</code>.
6128 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6129 * ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6130 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6131 * ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6132 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6133 * Raises an exception if +name+ is not a String:
6134 * ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)
6137 env_assoc(VALUE env
, VALUE key
)
6139 const char *s
= env_name(key
);
6140 VALUE e
= getenv_with_lock(s
);
6143 return rb_assoc_new(key
, e
);
6152 * ENV.value?(value) -> true or false
6153 * ENV.has_value?(value) -> true or false
6155 * Returns +true+ if +value+ is the value for some environment variable name, +false+ otherwise:
6156 * ENV.replace('foo' => '0', 'bar' => '1')
6157 * ENV.value?('0') # => true
6158 * ENV.has_value?('0') # => true
6159 * ENV.value?('2') # => false
6160 * ENV.has_value?('2') # => false
6163 env_has_value(VALUE dmy
, VALUE obj
)
6165 obj
= rb_check_string_type(obj
);
6166 if (NIL_P(obj
)) return Qnil
;
6172 char **env
= GET_ENVIRON(environ
);
6174 char *s
= strchr(*env
, '=');
6176 long len
= strlen(s
);
6177 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
6184 FREE_ENVIRON(environ
);
6193 * ENV.rassoc(value) -> [name, value] or nil
6195 * Returns a 2-element Array containing the name and value of the
6196 * *first* *found* environment variable that has value +value+, if one
6198 * ENV.replace('foo' => '0', 'bar' => '0')
6199 * ENV.rassoc('0') # => ["bar", "0"]
6200 * The order in which environment variables are examined is OS-dependent.
6201 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6203 * Returns +nil+ if there is no such environment variable.
6206 env_rassoc(VALUE dmy
, VALUE obj
)
6208 obj
= rb_check_string_type(obj
);
6209 if (NIL_P(obj
)) return Qnil
;
6211 VALUE result
= Qnil
;
6215 char **env
= GET_ENVIRON(environ
);
6218 const char *p
= *env
;
6219 char *s
= strchr(p
, '=');
6221 long len
= strlen(s
);
6222 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
6223 result
= rb_assoc_new(rb_str_new(p
, s
-p
-1), obj
);
6229 FREE_ENVIRON(environ
);
6238 * ENV.key(value) -> name or nil
6240 * Returns the name of the first environment variable with +value+, if it exists:
6241 * ENV.replace('foo' => '0', 'bar' => '0')
6242 * ENV.key('0') # => "foo"
6243 * The order in which environment variables are examined is OS-dependent.
6244 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6246 * Returns +nil+ if there is no such value.
6248 * Raises an exception if +value+ is invalid:
6249 * ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)
6250 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
6253 env_key(VALUE dmy
, VALUE value
)
6260 char **env
= GET_ENVIRON(environ
);
6262 char *s
= strchr(*env
, '=');
6264 long len
= strlen(s
);
6265 if (RSTRING_LEN(value
) == len
&& strncmp(s
, RSTRING_PTR(value
), len
) == 0) {
6266 str
= env_str_new(*env
, s
-*env
-1);
6272 FREE_ENVIRON(environ
);
6282 VALUE hash
= rb_hash_new();
6286 char **env
= GET_ENVIRON(environ
);
6288 char *s
= strchr(*env
, '=');
6290 rb_hash_aset(hash
, env_str_new(*env
, s
-*env
),
6295 FREE_ENVIRON(environ
);
6309 rb_env_to_hash(void)
6311 return env_to_hash();
6316 * ENV.to_hash -> hash of name/value pairs
6318 * Returns a Hash containing all name/value pairs from ENV:
6319 * ENV.replace('foo' => '0', 'bar' => '1')
6320 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6324 env_f_to_hash(VALUE _
)
6326 return env_to_hash();
6331 * ENV.to_h -> hash of name/value pairs
6332 * ENV.to_h {|name, value| block } -> hash of name/value pairs
6334 * With no block, returns a Hash containing all name/value pairs from ENV:
6335 * ENV.replace('foo' => '0', 'bar' => '1')
6336 * ENV.to_h # => {"bar"=>"1", "foo"=>"0"}
6337 * With a block, returns a Hash whose items are determined by the block.
6338 * Each name/value pair in ENV is yielded to the block.
6339 * The block must return a 2-element Array (name/value pair)
6340 * that is added to the return Hash as a key and value:
6341 * ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}
6342 * Raises an exception if the block does not return an Array:
6343 * ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))
6344 * Raises an exception if the block returns an Array of the wrong size:
6345 * ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
6350 VALUE hash
= env_to_hash();
6351 if (rb_block_given_p()) {
6352 hash
= rb_hash_to_h_block(hash
);
6359 * ENV.except(*keys) -> a_hash
6361 * Returns a hash except the given keys from ENV and their values.
6363 * ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
6364 * ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
6367 env_except(int argc
, VALUE
*argv
, VALUE _
)
6370 VALUE key
, hash
= env_to_hash();
6372 for (i
= 0; i
< argc
; i
++) {
6374 rb_hash_delete(hash
, key
);
6382 * ENV.reject { |name, value| block } -> hash of name/value pairs
6383 * ENV.reject -> an_enumerator
6385 * Yields each environment variable name and its value as a 2-element Array.
6386 * Returns a Hash whose items are determined by the block.
6387 * When the block returns a truthy value, the name/value pair is added to the return Hash;
6388 * otherwise the pair is ignored:
6389 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
6390 * ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6391 * Returns an Enumerator if no block given:
6393 * e.each { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6398 return rb_hash_delete_if(env_to_hash());
6401 NORETURN(static VALUE
env_freeze(VALUE self
));
6406 * Raises an exception:
6407 * ENV.freeze # Raises TypeError (cannot freeze ENV)
6410 env_freeze(VALUE self
)
6412 rb_raise(rb_eTypeError
, "cannot freeze ENV");
6413 UNREACHABLE_RETURN(self
);
6418 * ENV.shift -> [name, value] or nil
6420 * Removes the first environment variable from ENV and returns
6421 * a 2-element Array containing its name and value:
6422 * ENV.replace('foo' => '0', 'bar' => '1')
6423 * ENV.to_hash # => {'bar' => '1', 'foo' => '0'}
6424 * ENV.shift # => ['bar', '1']
6425 * ENV.to_hash # => {'foo' => '0'}
6426 * Exactly which environment variable is "first" is OS-dependent.
6427 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6429 * Returns +nil+ if the environment is empty.
6434 VALUE result
= Qnil
;
6439 char **env
= GET_ENVIRON(environ
);
6441 const char *p
= *env
;
6442 char *s
= strchr(p
, '=');
6444 key
= env_str_new(p
, s
-p
);
6445 VALUE val
= env_str_new2(getenv(RSTRING_PTR(key
)));
6446 result
= rb_assoc_new(key
, val
);
6449 FREE_ENVIRON(environ
);
6462 * ENV.invert -> hash of value/name pairs
6464 * Returns a Hash whose keys are the ENV values,
6465 * and whose values are the corresponding ENV names:
6466 * ENV.replace('foo' => '0', 'bar' => '1')
6467 * ENV.invert # => {"1"=>"bar", "0"=>"foo"}
6468 * For a duplicate ENV value, overwrites the hash entry:
6469 * ENV.replace('foo' => '0', 'bar' => '0')
6470 * ENV.invert # => {"0"=>"foo"}
6471 * Note that the order of the ENV processing is OS-dependent,
6472 * which means that the order of overwriting is also OS-dependent.
6473 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6478 return rb_hash_invert(env_to_hash());
6482 keylist_delete(VALUE keys
, VALUE key
)
6485 const char *keyptr
, *eptr
;
6486 RSTRING_GETMEM(key
, keyptr
, keylen
);
6487 /* Don't stop at first key, as it is possible to have
6488 multiple environment values with the same key.
6490 for (long i
=0; i
<RARRAY_LEN(keys
); i
++) {
6491 VALUE e
= RARRAY_AREF(keys
, i
);
6492 RSTRING_GETMEM(e
, eptr
, elen
);
6493 if (elen
!= keylen
) continue;
6494 if (!ENVNMATCH(keyptr
, eptr
, elen
)) continue;
6495 rb_ary_delete_at(keys
, i
);
6501 env_replace_i(VALUE key
, VALUE val
, VALUE keys
)
6506 keylist_delete(keys
, key
);
6512 * ENV.replace(hash) -> ENV
6514 * Replaces the entire content of the environment variables
6515 * with the name/value pairs in the given +hash+;
6518 * Replaces the content of ENV with the given pairs:
6519 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
6520 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6522 * Raises an exception if a name or value is invalid
6523 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6524 * ENV.replace('foo' => '0', :bar => '1') # Raises TypeError (no implicit conversion of Symbol into String)
6525 * ENV.replace('foo' => '0', 'bar' => 1) # Raises TypeError (no implicit conversion of Integer into String)
6526 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6529 env_replace(VALUE env
, VALUE hash
)
6534 keys
= env_keys(TRUE
);
6535 if (env
== hash
) return env
;
6536 hash
= to_hash(hash
);
6537 rb_hash_foreach(hash
, env_replace_i
, keys
);
6539 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
6540 env_delete(RARRAY_AREF(keys
, i
));
6547 env_update_i(VALUE key
, VALUE val
, VALUE _
)
6554 env_update_block_i(VALUE key
, VALUE val
, VALUE _
)
6556 VALUE oldval
= rb_f_getenv(Qnil
, key
);
6557 if (!NIL_P(oldval
)) {
6558 val
= rb_yield_values(3, key
, oldval
, val
);
6567 * ENV.update(*hashes) -> ENV
6568 * ENV.update(*hashes) { |name, env_val, hash_val| block } -> ENV
6570 * ENV.merge!(*hashes) -> ENV
6571 * ENV.merge!(*hashes) { |name, env_val, hash_val| block } -> ENV
6573 * Adds to ENV each key/value pair in the given +hash+; returns ENV:
6574 * ENV.replace('foo' => '0', 'bar' => '1')
6575 * ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
6576 * Deletes the ENV entry for a hash value that is +nil+:
6577 * ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
6578 * For an already-existing name, if no block given, overwrites the ENV value:
6579 * ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
6580 * For an already-existing name, if block given,
6581 * yields the name, its ENV value, and its hash value;
6582 * the block's return value becomes the new name:
6583 * ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
6584 * Raises an exception if a name or value is invalid
6585 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]);
6586 * ENV.replace('foo' => '0', 'bar' => '1')
6587 * ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String)
6588 * ENV # => {"bar"=>"1", "foo"=>"6"}
6589 * ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String)
6590 * ENV # => {"bar"=>"1", "foo"=>"7"}
6591 * Raises an exception if the block returns an invalid name:
6592 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6593 * ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String)
6594 * ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
6596 * Note that for the exceptions above,
6597 * hash pairs preceding an invalid name or value are processed normally;
6598 * those following are ignored.
6601 env_update(int argc
, VALUE
*argv
, VALUE env
)
6603 rb_foreach_func
*func
= rb_block_given_p() ?
6604 env_update_block_i
: env_update_i
;
6605 for (int i
= 0; i
< argc
; ++i
) {
6606 VALUE hash
= argv
[i
];
6607 if (env
== hash
) continue;
6608 hash
= to_hash(hash
);
6609 rb_hash_foreach(hash
, func
, 0);
6614 NORETURN(static VALUE
env_clone(int, VALUE
*, VALUE
));
6617 * ENV.clone(freeze: nil) # raises TypeError
6619 * Raises TypeError, because ENV is a wrapper for the process-wide
6620 * environment variables and a clone is useless.
6621 * Use #to_h to get a copy of ENV data as a hash.
6624 env_clone(int argc
, VALUE
*argv
, VALUE obj
)
6628 if (rb_scan_args(argc
, argv
, "0:", &opt
) < argc
) {
6629 rb_get_freeze_opt(1, &opt
);
6633 rb_raise(rb_eTypeError
, "Cannot clone ENV, use ENV.to_h to get a copy of ENV as a hash");
6636 NORETURN(static VALUE
env_dup(VALUE
));
6639 * ENV.dup # raises TypeError
6641 * Raises TypeError, because ENV is a singleton object.
6642 * Use #to_h to get a copy of ENV data as a hash.
6647 rb_raise(rb_eTypeError
, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash");
6650 static const rb_data_type_t env_data_type
= {
6658 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
| RUBY_TYPED_WB_PROTECTED
,
6662 * A +Hash+ maps each of its unique keys to a specific value.
6664 * A +Hash+ has certain similarities to an Array, but:
6665 * - An Array index is always an Integer.
6666 * - A +Hash+ key can be (almost) any object.
6668 * === +Hash+ \Data Syntax
6670 * The older syntax for +Hash+ data uses the "hash rocket," <tt>=></tt>:
6672 * h = {:foo => 0, :bar => 1, :baz => 2}
6673 * h # => {:foo=>0, :bar=>1, :baz=>2}
6675 * Alternatively, but only for a +Hash+ key that's a Symbol,
6676 * you can use a newer JSON-style syntax,
6677 * where each bareword becomes a Symbol:
6679 * h = {foo: 0, bar: 1, baz: 2}
6680 * h # => {:foo=>0, :bar=>1, :baz=>2}
6682 * You can also use a String in place of a bareword:
6684 * h = {'foo': 0, 'bar': 1, 'baz': 2}
6685 * h # => {:foo=>0, :bar=>1, :baz=>2}
6687 * And you can mix the styles:
6689 * h = {foo: 0, :bar => 1, 'baz': 2}
6690 * h # => {:foo=>0, :bar=>1, :baz=>2}
6692 * But it's an error to try the JSON-style syntax
6693 * for a key that's not a bareword or a String:
6695 * # Raises SyntaxError (syntax error, unexpected ':', expecting =>):
6698 * +Hash+ value can be omitted, meaning that value will be fetched from the context
6699 * by the name of the key:
6704 * h # => {:x=>0, :y=>100}
6708 * You can use a +Hash+ to give names to objects:
6710 * person = {name: 'Matz', language: 'Ruby'}
6711 * person # => {:name=>"Matz", :language=>"Ruby"}
6713 * You can use a +Hash+ to give names to method arguments:
6715 * def some_method(hash)
6718 * some_method({foo: 0, bar: 1, baz: 2}) # => {:foo=>0, :bar=>1, :baz=>2}
6720 * Note: when the last argument in a method call is a +Hash+,
6721 * the curly braces may be omitted:
6723 * some_method(foo: 0, bar: 1, baz: 2) # => {:foo=>0, :bar=>1, :baz=>2}
6725 * You can use a +Hash+ to initialize an object:
6728 * attr_accessor :name, :language
6729 * def initialize(hash)
6730 * self.name = hash[:name]
6731 * self.language = hash[:language]
6734 * matz = Dev.new(name: 'Matz', language: 'Ruby')
6735 * matz # => #<Dev: @name="Matz", @language="Ruby">
6737 * === Creating a +Hash+
6739 * You can create a +Hash+ object explicitly with:
6741 * - A {hash literal}[rdoc-ref:syntax/literals.rdoc@Hash+Literals].
6743 * You can convert certain objects to Hashes with:
6747 * You can create a +Hash+ by calling method Hash.new.
6749 * Create an empty +Hash+:
6755 * You can create a +Hash+ by calling method Hash.[].
6757 * Create an empty +Hash+:
6762 * Create a +Hash+ with initial entries:
6764 * h = Hash[foo: 0, bar: 1, baz: 2]
6765 * h # => {:foo=>0, :bar=>1, :baz=>2}
6767 * You can create a +Hash+ by using its literal form (curly braces).
6769 * Create an empty +Hash+:
6774 * Create a +Hash+ with initial entries:
6776 * h = {foo: 0, bar: 1, baz: 2}
6777 * h # => {:foo=>0, :bar=>1, :baz=>2}
6780 * === +Hash+ Value Basics
6782 * The simplest way to retrieve a +Hash+ value (instance method #[]):
6784 * h = {foo: 0, bar: 1, baz: 2}
6787 * The simplest way to create or update a +Hash+ value (instance method #[]=):
6789 * h = {foo: 0, bar: 1, baz: 2}
6790 * h[:bat] = 3 # => 3
6791 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
6792 * h[:foo] = 4 # => 4
6793 * h # => {:foo=>4, :bar=>1, :baz=>2, :bat=>3}
6795 * The simplest way to delete a +Hash+ entry (instance method #delete):
6797 * h = {foo: 0, bar: 1, baz: 2}
6798 * h.delete(:bar) # => 1
6799 * h # => {:foo=>0, :baz=>2}
6803 * A +Hash+ object presents its entries in the order of their creation. This is seen in:
6805 * - Iterative methods such as <tt>each</tt>, <tt>each_key</tt>, <tt>each_pair</tt>, <tt>each_value</tt>.
6806 * - Other order-sensitive methods such as <tt>shift</tt>, <tt>keys</tt>, <tt>values</tt>.
6807 * - The String returned by method <tt>inspect</tt>.
6809 * A new +Hash+ has its initial ordering per the given entries:
6811 * h = Hash[foo: 0, bar: 1]
6812 * h # => {:foo=>0, :bar=>1}
6814 * New entries are added at the end:
6817 * h # => {:foo=>0, :bar=>1, :baz=>2}
6819 * Updating a value does not affect the order:
6822 * h # => {:foo=>0, :bar=>1, :baz=>3}
6824 * But re-creating a deleted entry can affect the order:
6828 * h # => {:bar=>1, :baz=>3, :foo=>5}
6832 * ==== +Hash+ Key Equivalence
6834 * Two objects are treated as the same \hash key when their <code>hash</code> value
6835 * is identical and the two objects are <code>eql?</code> to each other.
6837 * ==== Modifying an Active +Hash+ Key
6839 * Modifying a +Hash+ key while it is in use damages the hash's index.
6841 * This +Hash+ has keys that are Arrays:
6843 * a0 = [ :foo, :bar ]
6844 * a1 = [ :baz, :bat ]
6845 * h = {a0 => 0, a1 => 1}
6846 * h.include?(a0) # => true
6848 * a0.hash # => 110002110
6850 * Modifying array element <tt>a0[0]</tt> changes its hash value:
6853 * a0.hash # => 1069447059
6855 * And damages the +Hash+ index:
6857 * h.include?(a0) # => false
6860 * You can repair the hash index using method +rehash+:
6862 * h.rehash # => {[:bam, :bar]=>0, [:baz, :bat]=>1}
6863 * h.include?(a0) # => true
6866 * A String key is always safe.
6867 * That's because an unfrozen String
6868 * passed as a key will be replaced by a duplicated and frozen String:
6871 * s.frozen? # => false
6873 * first_key = h.keys.first
6874 * first_key.frozen? # => true
6876 * ==== User-Defined +Hash+ Keys
6878 * To be useable as a +Hash+ key, objects must implement the methods <code>hash</code> and <code>eql?</code>.
6879 * Note: this requirement does not apply if the +Hash+ uses #compare_by_identity since comparison will then
6880 * rely on the keys' object id instead of <code>hash</code> and <code>eql?</code>.
6882 * Object defines basic implementation for <code>hash</code> and <code>eq?</code> that makes each object
6883 * a distinct key. Typically, user-defined classes will want to override these methods to provide meaningful
6884 * behavior, or for example inherit Struct that has useful definitions for these.
6886 * A typical implementation of <code>hash</code> is based on the
6887 * object's data while <code>eql?</code> is usually aliased to the overridden
6888 * <code>==</code> method:
6891 * attr_reader :author, :title
6893 * def initialize(author, title)
6899 * self.class === other &&
6900 * other.author == @author &&
6901 * other.title == @title
6907 * [self.class, @author, @title].hash
6911 * book1 = Book.new 'matz', 'Ruby in a Nutshell'
6912 * book2 = Book.new 'matz', 'Ruby in a Nutshell'
6916 * reviews[book1] = 'Great reference!'
6917 * reviews[book2] = 'Nice and compact!'
6919 * reviews.length #=> 1
6921 * === Default Values
6923 * The methods #[], #values_at and #dig need to return the value associated to a certain key.
6924 * When that key is not found, that value will be determined by its default proc (if any)
6925 * or else its default (initially `nil`).
6927 * You can retrieve the default value with method #default:
6930 * h.default # => nil
6932 * You can set the default value by passing an argument to method Hash.new or
6933 * with method #default=
6940 * This default value is returned for #[], #values_at and #dig when a key is
6943 * counts = {foo: 42}
6944 * counts.default # => nil (default)
6946 * counts[:bar] # => nil
6947 * counts.default = 0
6948 * counts[:bar] # => 0
6949 * counts.values_at(:foo, :bar, :baz) # => [42, 0, 0]
6950 * counts.dig(:bar) # => 0
6952 * Note that the default value is used without being duplicated. It is not advised to set
6953 * the default value to a mutable object:
6955 * synonyms = Hash.new([])
6956 * synonyms[:hello] # => []
6957 * synonyms[:hello] << :hi # => [:hi], but this mutates the default!
6958 * synonyms.default # => [:hi]
6959 * synonyms[:world] << :universe
6960 * synonyms[:world] # => [:hi, :universe], oops
6961 * synonyms.keys # => [], oops
6963 * To use a mutable object as default, it is recommended to use a default proc
6967 * When the default proc for a +Hash+ is set (i.e., not +nil+),
6968 * the default value returned by method #[] is determined by the default proc alone.
6970 * You can retrieve the default proc with method #default_proc:
6973 * h.default_proc # => nil
6975 * You can set the default proc by calling Hash.new with a block or
6976 * calling the method #default_proc=
6978 * h = Hash.new { |hash, key| "Default value for #{key}" }
6979 * h.default_proc.class # => Proc
6980 * h.default_proc = proc { |hash, key| "Default value for #{key.inspect}" }
6981 * h.default_proc.class # => Proc
6983 * When the default proc is set (i.e., not +nil+)
6984 * and method #[] is called with with a non-existent key,
6985 * #[] calls the default proc with both the +Hash+ object itself and the missing key,
6986 * then returns the proc's return value:
6988 * h = Hash.new { |hash, key| "Default value for #{key}" }
6989 * h[:nosuch] # => "Default value for nosuch"
6991 * Note that in the example above no entry for key +:nosuch+ is created:
6993 * h.include?(:nosuch) # => false
6995 * However, the proc itself can add a new entry:
6997 * synonyms = Hash.new { |hash, key| hash[key] = [] }
6998 * synonyms.include?(:hello) # => false
6999 * synonyms[:hello] << :hi # => [:hi]
7000 * synonyms[:world] << :universe # => [:universe]
7001 * synonyms.keys # => [:hello, :world]
7003 * Note that setting the default proc will clear the default value and vice versa.
7005 * Be aware that a default proc that modifies the hash is not thread-safe in the
7006 * sense that multiple threads can call into the default proc concurrently for the
7011 * First, what's elsewhere. \Class +Hash+:
7013 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
7014 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
7015 * which provides dozens of additional methods.
7017 * Here, class +Hash+ provides methods that are useful for:
7019 * - {Creating a Hash}[rdoc-ref:Hash@Methods+for+Creating+a+Hash]
7020 * - {Setting Hash State}[rdoc-ref:Hash@Methods+for+Setting+Hash+State]
7021 * - {Querying}[rdoc-ref:Hash@Methods+for+Querying]
7022 * - {Comparing}[rdoc-ref:Hash@Methods+for+Comparing]
7023 * - {Fetching}[rdoc-ref:Hash@Methods+for+Fetching]
7024 * - {Assigning}[rdoc-ref:Hash@Methods+for+Assigning]
7025 * - {Deleting}[rdoc-ref:Hash@Methods+for+Deleting]
7026 * - {Iterating}[rdoc-ref:Hash@Methods+for+Iterating]
7027 * - {Converting}[rdoc-ref:Hash@Methods+for+Converting]
7028 * - {Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values]
7029 * - {And more....}[rdoc-ref:Hash@Other+Methods]
7031 * \Class +Hash+ also includes methods from module Enumerable.
7033 * ==== Methods for Creating a +Hash+
7035 * - ::[]: Returns a new hash populated with given objects.
7036 * - ::new: Returns a new empty hash.
7037 * - ::try_convert: Returns a new hash created from a given object.
7039 * ==== Methods for Setting +Hash+ State
7041 * - #compare_by_identity: Sets +self+ to consider only identity in comparing keys.
7042 * - #default=: Sets the default to a given value.
7043 * - #default_proc=: Sets the default proc to a given proc.
7044 * - #rehash: Rebuilds the hash table by recomputing the hash index for each key.
7046 * ==== Methods for Querying
7048 * - #any?: Returns whether any element satisfies a given criterion.
7049 * - #compare_by_identity?: Returns whether the hash considers only identity when comparing keys.
7050 * - #default: Returns the default value, or the default value for a given key.
7051 * - #default_proc: Returns the default proc.
7052 * - #empty?: Returns whether there are no entries.
7053 * - #eql?: Returns whether a given object is equal to +self+.
7054 * - #hash: Returns the integer hash code.
7055 * - #has_value?: Returns whether a given object is a value in +self+.
7056 * - #include?, #has_key?, #member?, #key?: Returns whether a given object is a key in +self+.
7057 * - #length, #size: Returns the count of entries.
7058 * - #value?: Returns whether a given object is a value in +self+.
7060 * ==== Methods for Comparing
7062 * - #<: Returns whether +self+ is a proper subset of a given object.
7063 * - #<=: Returns whether +self+ is a subset of a given object.
7064 * - #==: Returns whether a given object is equal to +self+.
7065 * - #>: Returns whether +self+ is a proper superset of a given object
7066 * - #>=: Returns whether +self+ is a superset of a given object.
7068 * ==== Methods for Fetching
7070 * - #[]: Returns the value associated with a given key.
7071 * - #assoc: Returns a 2-element array containing a given key and its value.
7072 * - #dig: Returns the object in nested objects that is specified
7073 * by a given key and additional arguments.
7074 * - #fetch: Returns the value for a given key.
7075 * - #fetch_values: Returns array containing the values associated with given keys.
7076 * - #key: Returns the key for the first-found entry with a given value.
7077 * - #keys: Returns an array containing all keys in +self+.
7078 * - #rassoc: Returns a 2-element array consisting of the key and value
7079 * of the first-found entry having a given value.
7080 * - #values: Returns an array containing all values in +self+/
7081 * - #values_at: Returns an array containing values for given keys.
7083 * ==== Methods for Assigning
7085 * - #[]=, #store: Associates a given key with a given value.
7086 * - #merge: Returns the hash formed by merging each given hash into a copy of +self+.
7087 * - #merge!, #update: Merges each given hash into +self+.
7088 * - #replace: Replaces the entire contents of +self+ with the contents of a given hash.
7090 * ==== Methods for Deleting
7092 * These methods remove entries from +self+:
7094 * - #clear: Removes all entries from +self+.
7095 * - #compact!: Removes all +nil+-valued entries from +self+.
7096 * - #delete: Removes the entry for a given key.
7097 * - #delete_if: Removes entries selected by a given block.
7098 * - #filter!, #select!: Keep only those entries selected by a given block.
7099 * - #keep_if: Keep only those entries selected by a given block.
7100 * - #reject!: Removes entries selected by a given block.
7101 * - #shift: Removes and returns the first entry.
7103 * These methods return a copy of +self+ with some entries removed:
7105 * - #compact: Returns a copy of +self+ with all +nil+-valued entries removed.
7106 * - #except: Returns a copy of +self+ with entries removed for specified keys.
7107 * - #filter, #select: Returns a copy of +self+ with only those entries selected by a given block.
7108 * - #reject: Returns a copy of +self+ with entries removed as specified by a given block.
7109 * - #slice: Returns a hash containing the entries for given keys.
7111 * ==== Methods for Iterating
7112 * - #each, #each_pair: Calls a given block with each key-value pair.
7113 * - #each_key: Calls a given block with each key.
7114 * - #each_value: Calls a given block with each value.
7116 * ==== Methods for Converting
7118 * - #inspect, #to_s: Returns a new String containing the hash entries.
7119 * - #to_a: Returns a new array of 2-element arrays;
7120 * each nested array contains a key-value pair from +self+.
7121 * - #to_h: Returns +self+ if a +Hash+;
7122 * if a subclass of +Hash+, returns a +Hash+ containing the entries from +self+.
7123 * - #to_hash: Returns +self+.
7124 * - #to_proc: Returns a proc that maps a given key to its value.
7126 * ==== Methods for Transforming Keys and Values
7128 * - #transform_keys: Returns a copy of +self+ with modified keys.
7129 * - #transform_keys!: Modifies keys in +self+
7130 * - #transform_values: Returns a copy of +self+ with modified values.
7131 * - #transform_values!: Modifies values in +self+.
7133 * ==== Other Methods
7134 * - #flatten: Returns an array that is a 1-dimensional flattening of +self+.
7135 * - #invert: Returns a hash with the each key-value pair inverted.
7142 id_hash
= rb_intern_const("hash");
7143 id_flatten_bang
= rb_intern_const("flatten!");
7144 id_hash_iter_lev
= rb_make_internal_id();
7146 rb_cHash
= rb_define_class("Hash", rb_cObject
);
7148 rb_include_module(rb_cHash
, rb_mEnumerable
);
7150 rb_define_alloc_func(rb_cHash
, empty_hash_alloc
);
7151 rb_define_singleton_method(rb_cHash
, "[]", rb_hash_s_create
, -1);
7152 rb_define_singleton_method(rb_cHash
, "try_convert", rb_hash_s_try_convert
, 1);
7153 rb_define_method(rb_cHash
, "initialize", rb_hash_initialize
, -1);
7154 rb_define_method(rb_cHash
, "initialize_copy", rb_hash_replace
, 1);
7155 rb_define_method(rb_cHash
, "rehash", rb_hash_rehash
, 0);
7157 rb_define_method(rb_cHash
, "to_hash", rb_hash_to_hash
, 0);
7158 rb_define_method(rb_cHash
, "to_h", rb_hash_to_h
, 0);
7159 rb_define_method(rb_cHash
, "to_a", rb_hash_to_a
, 0);
7160 rb_define_method(rb_cHash
, "inspect", rb_hash_inspect
, 0);
7161 rb_define_alias(rb_cHash
, "to_s", "inspect");
7162 rb_define_method(rb_cHash
, "to_proc", rb_hash_to_proc
, 0);
7164 rb_define_method(rb_cHash
, "==", rb_hash_equal
, 1);
7165 rb_define_method(rb_cHash
, "[]", rb_hash_aref
, 1);
7166 rb_define_method(rb_cHash
, "hash", rb_hash_hash
, 0);
7167 rb_define_method(rb_cHash
, "eql?", rb_hash_eql
, 1);
7168 rb_define_method(rb_cHash
, "fetch", rb_hash_fetch_m
, -1);
7169 rb_define_method(rb_cHash
, "[]=", rb_hash_aset
, 2);
7170 rb_define_method(rb_cHash
, "store", rb_hash_aset
, 2);
7171 rb_define_method(rb_cHash
, "default", rb_hash_default
, -1);
7172 rb_define_method(rb_cHash
, "default=", rb_hash_set_default
, 1);
7173 rb_define_method(rb_cHash
, "default_proc", rb_hash_default_proc
, 0);
7174 rb_define_method(rb_cHash
, "default_proc=", rb_hash_set_default_proc
, 1);
7175 rb_define_method(rb_cHash
, "key", rb_hash_key
, 1);
7176 rb_define_method(rb_cHash
, "size", rb_hash_size
, 0);
7177 rb_define_method(rb_cHash
, "length", rb_hash_size
, 0);
7178 rb_define_method(rb_cHash
, "empty?", rb_hash_empty_p
, 0);
7180 rb_define_method(rb_cHash
, "each_value", rb_hash_each_value
, 0);
7181 rb_define_method(rb_cHash
, "each_key", rb_hash_each_key
, 0);
7182 rb_define_method(rb_cHash
, "each_pair", rb_hash_each_pair
, 0);
7183 rb_define_method(rb_cHash
, "each", rb_hash_each_pair
, 0);
7185 rb_define_method(rb_cHash
, "transform_keys", rb_hash_transform_keys
, -1);
7186 rb_define_method(rb_cHash
, "transform_keys!", rb_hash_transform_keys_bang
, -1);
7187 rb_define_method(rb_cHash
, "transform_values", rb_hash_transform_values
, 0);
7188 rb_define_method(rb_cHash
, "transform_values!", rb_hash_transform_values_bang
, 0);
7190 rb_define_method(rb_cHash
, "keys", rb_hash_keys
, 0);
7191 rb_define_method(rb_cHash
, "values", rb_hash_values
, 0);
7192 rb_define_method(rb_cHash
, "values_at", rb_hash_values_at
, -1);
7193 rb_define_method(rb_cHash
, "fetch_values", rb_hash_fetch_values
, -1);
7195 rb_define_method(rb_cHash
, "shift", rb_hash_shift
, 0);
7196 rb_define_method(rb_cHash
, "delete", rb_hash_delete_m
, 1);
7197 rb_define_method(rb_cHash
, "delete_if", rb_hash_delete_if
, 0);
7198 rb_define_method(rb_cHash
, "keep_if", rb_hash_keep_if
, 0);
7199 rb_define_method(rb_cHash
, "select", rb_hash_select
, 0);
7200 rb_define_method(rb_cHash
, "select!", rb_hash_select_bang
, 0);
7201 rb_define_method(rb_cHash
, "filter", rb_hash_select
, 0);
7202 rb_define_method(rb_cHash
, "filter!", rb_hash_select_bang
, 0);
7203 rb_define_method(rb_cHash
, "reject", rb_hash_reject
, 0);
7204 rb_define_method(rb_cHash
, "reject!", rb_hash_reject_bang
, 0);
7205 rb_define_method(rb_cHash
, "slice", rb_hash_slice
, -1);
7206 rb_define_method(rb_cHash
, "except", rb_hash_except
, -1);
7207 rb_define_method(rb_cHash
, "clear", rb_hash_clear
, 0);
7208 rb_define_method(rb_cHash
, "invert", rb_hash_invert
, 0);
7209 rb_define_method(rb_cHash
, "update", rb_hash_update
, -1);
7210 rb_define_method(rb_cHash
, "replace", rb_hash_replace
, 1);
7211 rb_define_method(rb_cHash
, "merge!", rb_hash_update
, -1);
7212 rb_define_method(rb_cHash
, "merge", rb_hash_merge
, -1);
7213 rb_define_method(rb_cHash
, "assoc", rb_hash_assoc
, 1);
7214 rb_define_method(rb_cHash
, "rassoc", rb_hash_rassoc
, 1);
7215 rb_define_method(rb_cHash
, "flatten", rb_hash_flatten
, -1);
7216 rb_define_method(rb_cHash
, "compact", rb_hash_compact
, 0);
7217 rb_define_method(rb_cHash
, "compact!", rb_hash_compact_bang
, 0);
7219 rb_define_method(rb_cHash
, "include?", rb_hash_has_key
, 1);
7220 rb_define_method(rb_cHash
, "member?", rb_hash_has_key
, 1);
7221 rb_define_method(rb_cHash
, "has_key?", rb_hash_has_key
, 1);
7222 rb_define_method(rb_cHash
, "has_value?", rb_hash_has_value
, 1);
7223 rb_define_method(rb_cHash
, "key?", rb_hash_has_key
, 1);
7224 rb_define_method(rb_cHash
, "value?", rb_hash_has_value
, 1);
7226 rb_define_method(rb_cHash
, "compare_by_identity", rb_hash_compare_by_id
, 0);
7227 rb_define_method(rb_cHash
, "compare_by_identity?", rb_hash_compare_by_id_p
, 0);
7229 rb_define_method(rb_cHash
, "any?", rb_hash_any_p
, -1);
7230 rb_define_method(rb_cHash
, "dig", rb_hash_dig
, -1);
7232 rb_define_method(rb_cHash
, "<=", rb_hash_le
, 1);
7233 rb_define_method(rb_cHash
, "<", rb_hash_lt
, 1);
7234 rb_define_method(rb_cHash
, ">=", rb_hash_ge
, 1);
7235 rb_define_method(rb_cHash
, ">", rb_hash_gt
, 1);
7237 rb_define_method(rb_cHash
, "deconstruct_keys", rb_hash_deconstruct_keys
, 1);
7239 rb_define_singleton_method(rb_cHash
, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p
, 1);
7240 rb_define_singleton_method(rb_cHash
, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash
, 1);
7242 /* Document-class: ENV
7244 * +ENV+ is a hash-like accessor for environment variables.
7246 * === Interaction with the Operating System
7248 * The +ENV+ object interacts with the operating system's environment variables:
7250 * - When you get the value for a name in +ENV+, the value is retrieved from among the current environment variables.
7251 * - When you create or set a name-value pair in +ENV+, the name and value are immediately set in the environment variables.
7252 * - When you delete a name-value pair in +ENV+, it is immediately deleted from the environment variables.
7254 * === Names and Values
7256 * Generally, a name or value is a String.
7258 * ==== Valid Names and Values
7260 * Each name or value must be one of the following:
7263 * - An object that responds to \#to_str by returning a String, in which case that String will be used as the name or value.
7265 * ==== Invalid Names and Values
7269 * - May not be the empty string:
7271 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv())
7273 * - May not contain character <code>"="</code>:
7275 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv(=))
7277 * A new name or value:
7279 * - May not be a non-String that does not respond to \#to_str:
7281 * ENV['foo'] = Object.new
7282 * # Raises TypeError (no implicit conversion of Object into String)
7283 * ENV[Object.new] = '0'
7284 * # Raises TypeError (no implicit conversion of Object into String)
7286 * - May not contain the NUL character <code>"\0"</code>:
7289 * # Raises ArgumentError (bad environment variable value: contains null byte)
7291 * # Raises ArgumentError (bad environment variable name: contains null byte)
7293 * - May not have an ASCII-incompatible encoding such as UTF-16LE or ISO-2022-JP:
7295 * ENV['foo'] = '0'.force_encoding(Encoding::ISO_2022_JP)
7296 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7297 * ENV["foo".force_encoding(Encoding::ISO_2022_JP)] = '0'
7298 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7300 * === About Ordering
7302 * +ENV+ enumerates its name/value pairs in the order found
7303 * in the operating system's environment variables.
7304 * Therefore the ordering of +ENV+ content is OS-dependent, and may be indeterminate.
7306 * This will be seen in:
7307 * - A Hash returned by an +ENV+ method.
7308 * - An Enumerator returned by an +ENV+ method.
7309 * - An Array returned by ENV.keys, ENV.values, or ENV.to_a.
7310 * - The String returned by ENV.inspect.
7311 * - The Array returned by ENV.shift.
7312 * - The name returned by ENV.key.
7314 * === About the Examples
7315 * Some methods in +ENV+ return +ENV+ itself. Typically, there are many environment variables.
7316 * It's not useful to display a large +ENV+ in the examples here,
7317 * so most example snippets begin by resetting the contents of +ENV+:
7318 * - ENV.replace replaces +ENV+ with a new collection of entries.
7319 * - ENV.clear empties +ENV+.
7323 * First, what's elsewhere. \Class +ENV+:
7325 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
7326 * - Extends {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
7328 * Here, class +ENV+ provides methods that are useful for:
7330 * - {Querying}[rdoc-ref:ENV@Methods+for+Querying]
7331 * - {Assigning}[rdoc-ref:ENV@Methods+for+Assigning]
7332 * - {Deleting}[rdoc-ref:ENV@Methods+for+Deleting]
7333 * - {Iterating}[rdoc-ref:ENV@Methods+for+Iterating]
7334 * - {Converting}[rdoc-ref:ENV@Methods+for+Converting]
7335 * - {And more ....}[rdoc-ref:ENV@More+Methods]
7337 * ==== Methods for Querying
7339 * - ::[]: Returns the value for the given environment variable name if it exists:
7340 * - ::empty?: Returns whether +ENV+ is empty.
7341 * - ::has_value?, ::value?: Returns whether the given value is in +ENV+.
7342 * - ::include?, ::has_key?, ::key?, ::member?: Returns whether the given name
7344 * - ::key: Returns the name of the first entry with the given value.
7345 * - ::size, ::length: Returns the number of entries.
7346 * - ::value?: Returns whether any entry has the given value.
7348 * ==== Methods for Assigning
7350 * - ::[]=, ::store: Creates, updates, or deletes the named environment variable.
7351 * - ::clear: Removes every environment variable; returns +ENV+:
7352 * - ::update, ::merge!: Adds to +ENV+ each key/value pair in the given hash.
7353 * - ::replace: Replaces the entire content of the +ENV+
7354 * with the name/value pairs in the given hash.
7356 * ==== Methods for Deleting
7358 * - ::delete: Deletes the named environment variable name if it exists.
7359 * - ::delete_if: Deletes entries selected by the block.
7360 * - ::keep_if: Deletes entries not selected by the block.
7361 * - ::reject!: Similar to #delete_if, but returns +nil+ if no change was made.
7362 * - ::select!, ::filter!: Deletes entries selected by the block.
7363 * - ::shift: Removes and returns the first entry.
7365 * ==== Methods for Iterating
7367 * - ::each, ::each_pair: Calls the block with each name/value pair.
7368 * - ::each_key: Calls the block with each name.
7369 * - ::each_value: Calls the block with each value.
7371 * ==== Methods for Converting
7373 * - ::assoc: Returns a 2-element array containing the name and value
7374 * of the named environment variable if it exists:
7375 * - ::clone: Returns +ENV+ (and issues a warning).
7376 * - ::except: Returns a hash of all name/value pairs except those given.
7377 * - ::fetch: Returns the value for the given name.
7378 * - ::inspect: Returns the contents of +ENV+ as a string.
7379 * - ::invert: Returns a hash whose keys are the +ENV+ values,
7380 and whose values are the corresponding +ENV+ names.
7381 * - ::keys: Returns an array of all names.
7382 * - ::rassoc: Returns the name and value of the first found entry
7383 * that has the given value.
7384 * - ::reject: Returns a hash of those entries not rejected by the block.
7385 * - ::select, ::filter: Returns a hash of name/value pairs selected by the block.
7386 * - ::slice: Returns a hash of the given names and their corresponding values.
7387 * - ::to_a: Returns the entries as an array of 2-element Arrays.
7388 * - ::to_h: Returns a hash of entries selected by the block.
7389 * - ::to_hash: Returns a hash of all entries.
7390 * - ::to_s: Returns the string <tt>'ENV'</tt>.
7391 * - ::values: Returns all values as an array.
7392 * - ::values_at: Returns an array of the values for the given name.
7396 * - ::dup: Raises an exception.
7397 * - ::freeze: Raises an exception.
7398 * - ::rehash: Returns +nil+, without modifying +ENV+.
7403 * Hack to get RDoc to regard ENV as a class:
7404 * envtbl = rb_define_class("ENV", rb_cObject);
7406 origenviron
= environ
;
7407 envtbl
= TypedData_Wrap_Struct(rb_cObject
, &env_data_type
, NULL
);
7408 rb_extend_object(envtbl
, rb_mEnumerable
);
7409 FL_SET_RAW(envtbl
, RUBY_FL_SHAREABLE
);
7412 rb_define_singleton_method(envtbl
, "[]", rb_f_getenv
, 1);
7413 rb_define_singleton_method(envtbl
, "fetch", env_fetch
, -1);
7414 rb_define_singleton_method(envtbl
, "[]=", env_aset_m
, 2);
7415 rb_define_singleton_method(envtbl
, "store", env_aset_m
, 2);
7416 rb_define_singleton_method(envtbl
, "each", env_each_pair
, 0);
7417 rb_define_singleton_method(envtbl
, "each_pair", env_each_pair
, 0);
7418 rb_define_singleton_method(envtbl
, "each_key", env_each_key
, 0);
7419 rb_define_singleton_method(envtbl
, "each_value", env_each_value
, 0);
7420 rb_define_singleton_method(envtbl
, "delete", env_delete_m
, 1);
7421 rb_define_singleton_method(envtbl
, "delete_if", env_delete_if
, 0);
7422 rb_define_singleton_method(envtbl
, "keep_if", env_keep_if
, 0);
7423 rb_define_singleton_method(envtbl
, "slice", env_slice
, -1);
7424 rb_define_singleton_method(envtbl
, "except", env_except
, -1);
7425 rb_define_singleton_method(envtbl
, "clear", env_clear
, 0);
7426 rb_define_singleton_method(envtbl
, "reject", env_reject
, 0);
7427 rb_define_singleton_method(envtbl
, "reject!", env_reject_bang
, 0);
7428 rb_define_singleton_method(envtbl
, "select", env_select
, 0);
7429 rb_define_singleton_method(envtbl
, "select!", env_select_bang
, 0);
7430 rb_define_singleton_method(envtbl
, "filter", env_select
, 0);
7431 rb_define_singleton_method(envtbl
, "filter!", env_select_bang
, 0);
7432 rb_define_singleton_method(envtbl
, "shift", env_shift
, 0);
7433 rb_define_singleton_method(envtbl
, "freeze", env_freeze
, 0);
7434 rb_define_singleton_method(envtbl
, "invert", env_invert
, 0);
7435 rb_define_singleton_method(envtbl
, "replace", env_replace
, 1);
7436 rb_define_singleton_method(envtbl
, "update", env_update
, -1);
7437 rb_define_singleton_method(envtbl
, "merge!", env_update
, -1);
7438 rb_define_singleton_method(envtbl
, "inspect", env_inspect
, 0);
7439 rb_define_singleton_method(envtbl
, "rehash", env_none
, 0);
7440 rb_define_singleton_method(envtbl
, "to_a", env_to_a
, 0);
7441 rb_define_singleton_method(envtbl
, "to_s", env_to_s
, 0);
7442 rb_define_singleton_method(envtbl
, "key", env_key
, 1);
7443 rb_define_singleton_method(envtbl
, "size", env_size
, 0);
7444 rb_define_singleton_method(envtbl
, "length", env_size
, 0);
7445 rb_define_singleton_method(envtbl
, "empty?", env_empty_p
, 0);
7446 rb_define_singleton_method(envtbl
, "keys", env_f_keys
, 0);
7447 rb_define_singleton_method(envtbl
, "values", env_f_values
, 0);
7448 rb_define_singleton_method(envtbl
, "values_at", env_values_at
, -1);
7449 rb_define_singleton_method(envtbl
, "include?", env_has_key
, 1);
7450 rb_define_singleton_method(envtbl
, "member?", env_has_key
, 1);
7451 rb_define_singleton_method(envtbl
, "has_key?", env_has_key
, 1);
7452 rb_define_singleton_method(envtbl
, "has_value?", env_has_value
, 1);
7453 rb_define_singleton_method(envtbl
, "key?", env_has_key
, 1);
7454 rb_define_singleton_method(envtbl
, "value?", env_has_value
, 1);
7455 rb_define_singleton_method(envtbl
, "to_hash", env_f_to_hash
, 0);
7456 rb_define_singleton_method(envtbl
, "to_h", env_to_h
, 0);
7457 rb_define_singleton_method(envtbl
, "assoc", env_assoc
, 1);
7458 rb_define_singleton_method(envtbl
, "rassoc", env_rassoc
, 1);
7459 rb_define_singleton_method(envtbl
, "clone", env_clone
, -1);
7460 rb_define_singleton_method(envtbl
, "dup", env_dup
, 0);
7462 VALUE envtbl_class
= rb_singleton_class(envtbl
);
7463 rb_undef_method(envtbl_class
, "initialize");
7464 rb_undef_method(envtbl_class
, "initialize_clone");
7465 rb_undef_method(envtbl_class
, "initialize_copy");
7466 rb_undef_method(envtbl_class
, "initialize_dup");
7469 * +ENV+ is a Hash-like accessor for environment variables.
7471 * See ENV (the class) for more details.
7473 rb_define_global_const("ENV", envtbl
);
7476 ruby_register_rollback_func_for_ensure(hash_foreach_ensure
, hash_foreach_ensure_rollback
);
7478 HASH_ASSERT(sizeof(ar_hint_t
) * RHASH_AR_TABLE_MAX_SIZE
== sizeof(VALUE
));