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"
55 * 1: RHASH_PASS_AS_KEYWORDS
56 * The hash is flagged as Ruby 2 keywords hash.
57 * 2: RHASH_PROC_DEFAULT
58 * The hash has a default proc (rather than a default value).
59 * 3: RHASH_ST_TABLE_FLAG
60 * The hash uses a ST table (rather than an AR table).
61 * 4-7: RHASH_AR_TABLE_SIZE_MASK
62 * The size of the AR table.
63 * 8-11: RHASH_AR_TABLE_BOUND_MASK
64 * The bounds of the AR table.
65 * 13-19: RHASH_LEV_MASK
66 * The iterational level of the hash. Used to prevent modifications
67 * to the hash during interation.
75 #include "internal/gc.h"
78 #define SET_DEFAULT(hash, ifnone) ( \
79 FL_UNSET_RAW(hash, RHASH_PROC_DEFAULT), \
80 RHASH_SET_IFNONE(hash, ifnone))
82 #define SET_PROC_DEFAULT(hash, proc) set_proc_default(hash, proc)
84 #define COPY_DEFAULT(hash, hash2) copy_default(RHASH(hash), RHASH(hash2))
87 copy_default(struct RHash
*hash
, const struct RHash
*hash2
)
89 hash
->basic
.flags
&= ~RHASH_PROC_DEFAULT
;
90 hash
->basic
.flags
|= hash2
->basic
.flags
& RHASH_PROC_DEFAULT
;
91 RHASH_SET_IFNONE(hash
, RHASH_IFNONE((VALUE
)hash2
));
94 static VALUE
rb_hash_s_try_convert(VALUE
, VALUE
);
98 * 1. Check mutate st_* functions
107 rb_hash_freeze(VALUE hash
)
109 return rb_obj_freeze(hash
);
115 static ID id_hash
, id_flatten_bang
;
116 static ID id_hash_iter_lev
;
118 #define id_default idDefault
121 rb_hash_set_ifnone(VALUE hash
, VALUE ifnone
)
123 RB_OBJ_WRITE(hash
, (&RHASH(hash
)->ifnone
), ifnone
);
128 rb_any_cmp(VALUE a
, VALUE b
)
130 if (a
== b
) return 0;
131 if (RB_TYPE_P(a
, T_STRING
) && RBASIC(a
)->klass
== rb_cString
&&
132 RB_TYPE_P(b
, T_STRING
) && RBASIC(b
)->klass
== rb_cString
) {
133 return rb_str_hash_cmp(a
, b
);
135 if (UNDEF_P(a
) || UNDEF_P(b
)) return -1;
136 if (SYMBOL_P(a
) && SYMBOL_P(b
)) {
140 return !rb_eql(a
, b
);
144 hash_recursive(VALUE obj
, VALUE arg
, int recurse
)
146 if (recurse
) return INT2FIX(0);
147 return rb_funcallv(obj
, id_hash
, 0, 0);
150 static long rb_objid_hash(st_index_t index
);
153 dbl_to_index(double d
)
155 union {double d
; st_index_t i
;} u
;
161 rb_dbl_long_hash(double d
)
163 /* normalize -0.0 to 0.0 */
164 if (d
== 0.0) d
= 0.0;
165 #if SIZEOF_INT == SIZEOF_VOIDP
166 return rb_memhash(&d
, sizeof(d
));
168 return rb_objid_hash(dbl_to_index(d
));
173 any_hash(VALUE a
, st_index_t (*other_func
)(VALUE
))
180 if (STATIC_SYM_P(a
)) {
181 hnum
= a
>> (RUBY_SPECIAL_SHIFT
+ ID_SCOPE_SHIFT
);
182 hnum
= rb_hash_start(hnum
);
185 hnum
= RSYMBOL(a
)->hashval
;
192 hnum
= rb_objid_hash((st_index_t
)a
);
195 hnum
= rb_str_hash(a
);
198 hval
= rb_big_hash(a
);
199 hnum
= FIX2LONG(hval
);
201 case T_FLOAT
: /* prevent pathological behavior: [Bug #10761] */
202 hnum
= rb_dbl_long_hash(rb_float_value(a
));
205 hnum
= other_func(a
);
207 if ((SIGNED_VALUE
)hnum
> 0)
214 VALUE
rb_obj_hash(VALUE obj
);
215 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
);
218 obj_any_hash(VALUE obj
)
221 VALUE klass
= CLASS_OF(obj
);
223 const rb_callable_method_entry_t
*cme
= rb_callable_method_entry(klass
, id_hash
);
224 if (cme
&& METHOD_ENTRY_BASIC(cme
)) {
225 // Optimize away the frame push overhead if it's the default Kernel#hash
226 if (cme
->def
->type
== VM_METHOD_TYPE_CFUNC
&& cme
->def
->body
.cfunc
.func
== (rb_cfunc_t
)rb_obj_hash
) {
227 hval
= rb_obj_hash(obj
);
229 else if (RBASIC_CLASS(cme
->defined_class
) == rb_mKernel
) {
230 hval
= rb_vm_call0(GET_EC(), obj
, id_hash
, 0, 0, cme
, 0);
236 hval
= rb_exec_recursive_outer_mid(hash_recursive
, obj
, 0, id_hash
);
239 while (!FIXNUM_P(hval
)) {
240 if (RB_TYPE_P(hval
, T_BIGNUM
)) {
243 sign
= rb_integer_pack(hval
, &ul
, 1, sizeof(ul
), 0,
244 INTEGER_PACK_NATIVE_BYTE_ORDER
);
246 hval
= LONG2FIX(ul
| FIXNUM_MIN
);
249 hval
= LONG2FIX(ul
& FIXNUM_MAX
);
252 hval
= rb_to_int(hval
);
255 return FIX2LONG(hval
);
261 return any_hash(a
, obj_any_hash
);
267 return LONG2FIX(any_hash(obj
, obj_any_hash
));
271 /* Here is a hash function for 64-bit key. It is about 5 times faster
272 (2 times faster when uint128 type is absent) on Haswell than
273 tailored Spooky or City hash function can be. */
275 /* Here we two primes with random bit generation. */
276 static const uint64_t prime1
= ((uint64_t)0x2e0bb864 << 32) | 0xe9ea7df5;
277 static const uint32_t prime2
= 0x830fcab9;
280 static inline uint64_t
281 mult_and_mix(uint64_t m1
, uint64_t m2
)
283 #if defined HAVE_UINT128_T
284 uint128_t r
= (uint128_t
) m1
* (uint128_t
) m2
;
285 return (uint64_t) (r
>> 64) ^ (uint64_t) r
;
287 uint64_t hm1
= m1
>> 32, hm2
= m2
>> 32;
288 uint64_t lm1
= m1
, lm2
= m2
;
289 uint64_t v64_128
= hm1
* hm2
;
290 uint64_t v32_96
= hm1
* lm2
+ lm1
* hm2
;
291 uint64_t v1_32
= lm1
* lm2
;
293 return (v64_128
+ (v32_96
>> 32)) ^ ((v32_96
<< 32) + v1_32
);
297 static inline uint64_t
298 key64_hash(uint64_t key
, uint32_t seed
)
300 return mult_and_mix(key
+ seed
, prime1
);
303 /* Should cast down the result for each purpose */
304 #define st_index_hash(index) key64_hash(rb_hash_start(index), prime2)
307 rb_objid_hash(st_index_t index
)
309 return (long)st_index_hash(index
);
313 objid_hash(VALUE obj
)
315 VALUE object_id
= rb_obj_id(obj
);
316 if (!FIXNUM_P(object_id
))
317 object_id
= rb_big_hash(object_id
);
319 #if SIZEOF_LONG == SIZEOF_VOIDP
320 return (st_index_t
)st_index_hash((st_index_t
)NUM2LONG(object_id
));
321 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
322 return (st_index_t
)st_index_hash((st_index_t
)NUM2LL(object_id
));
328 * obj.hash -> integer
330 * Generates an Integer hash value for this object. This function must have the
331 * property that <code>a.eql?(b)</code> implies <code>a.hash == b.hash</code>.
333 * The hash value is used along with #eql? by the Hash class to determine if
334 * two objects reference the same hash key. Any hash value that exceeds the
335 * capacity of an Integer will be truncated before being used.
337 * The hash value for an object may not be identical across invocations or
338 * implementations of Ruby. If you need a stable identifier across Ruby
339 * invocations and implementations you will need to generate one with a custom
342 * Certain core classes such as Integer use built-in hash calculations and
343 * do not call the #hash method when used as a hash key.
345 * When implementing your own #hash based on multiple values, the best
346 * practice is to combine the class and any values using the hash code of an
352 * [self.class, a, b, c].hash
355 * The reason for this is that the Array#hash method already has logic for
356 * safely and efficiently combining multiple hash values.
362 rb_obj_hash(VALUE obj
)
364 long hnum
= any_hash(obj
, objid_hash
);
368 static const struct st_hash_type objhash
= {
373 #define rb_ident_cmp st_numcmp
376 rb_ident_hash(st_data_t n
)
378 #ifdef USE_FLONUM /* RUBY */
380 * - flonum (on 64-bit) is pathologically bad, mix the actual
381 * float value in, but do not use the float value as-is since
382 * many integers get interpreted as 2.0 or -2.0 [Bug #10761]
385 n
^= dbl_to_index(rb_float_value(n
));
389 return (st_index_t
)st_index_hash((st_index_t
)n
);
392 #define identhash rb_hashtype_ident
393 const struct st_hash_type rb_hashtype_ident
= {
398 #define RHASH_IDENTHASH_P(hash) (RHASH_TYPE(hash) == &identhash)
399 #define RHASH_STRING_KEY_P(hash, key) (!RHASH_IDENTHASH_P(hash) && (rb_obj_class(key) == rb_cString))
401 typedef st_index_t st_hash_t
;
404 * RHASH_AR_TABLE_P(h):
405 * RHASH_AR_TABLE points to ar_table.
407 * !RHASH_AR_TABLE_P(h):
408 * RHASH_ST_TABLE points st_table.
411 #define RHASH_AR_TABLE_MAX_BOUND RHASH_AR_TABLE_MAX_SIZE
413 #define RHASH_AR_TABLE_REF(hash, n) (&RHASH_AR_TABLE(hash)->pairs[n])
414 #define RHASH_AR_CLEARED_HINT 0xff
416 static inline st_hash_t
417 ar_do_hash(st_data_t key
)
419 return (st_hash_t
)rb_any_hash(key
);
422 static inline ar_hint_t
423 ar_do_hash_hint(st_hash_t hash_value
)
425 return (ar_hint_t
)hash_value
;
428 static inline ar_hint_t
429 ar_hint(VALUE hash
, unsigned int index
)
431 return RHASH_AR_TABLE(hash
)->ar_hint
.ary
[index
];
435 ar_hint_set_hint(VALUE hash
, unsigned int index
, ar_hint_t hint
)
437 RHASH_AR_TABLE(hash
)->ar_hint
.ary
[index
] = hint
;
441 ar_hint_set(VALUE hash
, unsigned int index
, st_hash_t hash_value
)
443 ar_hint_set_hint(hash
, index
, ar_do_hash_hint(hash_value
));
447 ar_clear_entry(VALUE hash
, unsigned int index
)
449 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
451 ar_hint_set_hint(hash
, index
, RHASH_AR_CLEARED_HINT
);
455 ar_cleared_entry(VALUE hash
, unsigned int index
)
457 if (ar_hint(hash
, index
) == RHASH_AR_CLEARED_HINT
) {
458 /* RHASH_AR_CLEARED_HINT is only a hint, not mean cleared entry,
459 * so you need to check key == Qundef
461 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
462 return UNDEF_P(pair
->key
);
470 ar_set_entry(VALUE hash
, unsigned int index
, st_data_t key
, st_data_t val
, st_hash_t hash_value
)
472 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, index
);
475 ar_hint_set(hash
, index
, hash_value
);
478 #define RHASH_AR_TABLE_SIZE(h) (HASH_ASSERT(RHASH_AR_TABLE_P(h)), \
479 RHASH_AR_TABLE_SIZE_RAW(h))
481 #define RHASH_AR_TABLE_BOUND_RAW(h) \
482 ((unsigned int)((RBASIC(h)->flags >> RHASH_AR_TABLE_BOUND_SHIFT) & \
483 (RHASH_AR_TABLE_BOUND_MASK >> RHASH_AR_TABLE_BOUND_SHIFT)))
485 #define RHASH_ST_TABLE_SET(h, s) rb_hash_st_table_set(h, s)
486 #define RHASH_TYPE(hash) (RHASH_AR_TABLE_P(hash) ? &objhash : RHASH_ST_TABLE(hash)->type)
488 #define HASH_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(HASH_DEBUG, expr, #expr)
490 static inline unsigned int
491 RHASH_AR_TABLE_BOUND(VALUE h
)
493 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
494 const unsigned int bound
= RHASH_AR_TABLE_BOUND_RAW(h
);
495 HASH_ASSERT(bound
<= RHASH_AR_TABLE_MAX_SIZE
);
500 #define hash_verify(hash) hash_verify_(hash, __FILE__, __LINE__)
503 rb_hash_dump(VALUE hash
)
505 rb_obj_info_dump(hash
);
507 if (RHASH_AR_TABLE_P(hash
)) {
508 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
510 fprintf(stderr
, " size:%u bound:%u\n",
511 RHASH_AR_TABLE_SIZE(hash
), bound
);
513 for (i
=0; i
<bound
; i
++) {
516 if (!ar_cleared_entry(hash
, i
)) {
517 char b1
[0x100], b2
[0x100];
518 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
521 fprintf(stderr
, " %d key:%s val:%s hint:%02x\n", i
,
522 rb_raw_obj_info(b1
, 0x100, k
),
523 rb_raw_obj_info(b2
, 0x100, v
),
527 fprintf(stderr
, " %d empty\n", i
);
534 hash_verify_(VALUE hash
, const char *file
, int line
)
536 HASH_ASSERT(RB_TYPE_P(hash
, T_HASH
));
538 if (RHASH_AR_TABLE_P(hash
)) {
539 unsigned i
, n
= 0, bound
= RHASH_AR_TABLE_BOUND(hash
);
541 for (i
=0; i
<bound
; i
++) {
543 if (!ar_cleared_entry(hash
, i
)) {
544 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
547 HASH_ASSERT(!UNDEF_P(k
));
548 HASH_ASSERT(!UNDEF_P(v
));
552 if (n
!= RHASH_AR_TABLE_SIZE(hash
)) {
553 rb_bug("n:%u, RHASH_AR_TABLE_SIZE:%u", n
, RHASH_AR_TABLE_SIZE(hash
));
557 HASH_ASSERT(RHASH_ST_TABLE(hash
) != NULL
);
558 HASH_ASSERT(RHASH_AR_TABLE_SIZE_RAW(hash
) == 0);
559 HASH_ASSERT(RHASH_AR_TABLE_BOUND_RAW(hash
) == 0);
566 #define hash_verify(h) ((void)0)
570 RHASH_TABLE_EMPTY_P(VALUE hash
)
572 return RHASH_SIZE(hash
) == 0;
575 #define RHASH_SET_ST_FLAG(h) FL_SET_RAW(h, RHASH_ST_TABLE_FLAG)
576 #define RHASH_UNSET_ST_FLAG(h) FL_UNSET_RAW(h, RHASH_ST_TABLE_FLAG)
579 hash_st_table_init(VALUE hash
, const struct st_hash_type
*type
, st_index_t size
)
581 st_init_existing_table_with_size(RHASH_ST_TABLE(hash
), type
, size
);
582 RHASH_SET_ST_FLAG(hash
);
586 rb_hash_st_table_set(VALUE hash
, st_table
*st
)
588 HASH_ASSERT(st
!= NULL
);
589 RHASH_SET_ST_FLAG(hash
);
591 *RHASH_ST_TABLE(hash
) = *st
;
595 RHASH_AR_TABLE_BOUND_SET(VALUE h
, st_index_t n
)
597 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
598 HASH_ASSERT(n
<= RHASH_AR_TABLE_MAX_BOUND
);
600 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_BOUND_MASK
;
601 RBASIC(h
)->flags
|= n
<< RHASH_AR_TABLE_BOUND_SHIFT
;
605 RHASH_AR_TABLE_SIZE_SET(VALUE h
, st_index_t n
)
607 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
608 HASH_ASSERT(n
<= RHASH_AR_TABLE_MAX_SIZE
);
610 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_SIZE_MASK
;
611 RBASIC(h
)->flags
|= n
<< RHASH_AR_TABLE_SIZE_SHIFT
;
615 HASH_AR_TABLE_SIZE_ADD(VALUE h
, st_index_t n
)
617 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
619 RHASH_AR_TABLE_SIZE_SET(h
, RHASH_AR_TABLE_SIZE(h
) + n
);
624 #define RHASH_AR_TABLE_SIZE_INC(h) HASH_AR_TABLE_SIZE_ADD(h, 1)
627 RHASH_AR_TABLE_SIZE_DEC(VALUE h
)
629 HASH_ASSERT(RHASH_AR_TABLE_P(h
));
630 int new_size
= RHASH_AR_TABLE_SIZE(h
) - 1;
633 RHASH_AR_TABLE_SIZE_SET(h
, new_size
);
636 RHASH_AR_TABLE_SIZE_SET(h
, 0);
637 RHASH_AR_TABLE_BOUND_SET(h
, 0);
643 RHASH_AR_TABLE_CLEAR(VALUE h
)
645 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_SIZE_MASK
;
646 RBASIC(h
)->flags
&= ~RHASH_AR_TABLE_BOUND_MASK
;
648 memset(RHASH_AR_TABLE(h
), 0, sizeof(ar_table
));
651 NOINLINE(static int ar_equal(VALUE x
, VALUE y
));
654 ar_equal(VALUE x
, VALUE y
)
656 return rb_any_cmp(x
, y
) == 0;
660 ar_find_entry_hint(VALUE hash
, ar_hint_t hint
, st_data_t key
)
662 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
663 const ar_hint_t
*hints
= RHASH_AR_TABLE(hash
)->ar_hint
.ary
;
665 /* if table is NULL, then bound also should be 0 */
667 for (i
= 0; i
< bound
; i
++) {
668 if (hints
[i
] == hint
) {
669 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
670 if (ar_equal(key
, pair
->key
)) {
671 RB_DEBUG_COUNTER_INC(artable_hint_hit
);
677 static char fname
[256];
680 if (pid
!= getpid()) {
681 snprintf(fname
, sizeof(fname
), "/tmp/ruby-armiss.%d", pid
= getpid());
682 if ((fp
= fopen(fname
, "w")) == NULL
) rb_bug("fopen");
685 st_hash_t h1
= ar_do_hash(key
);
686 st_hash_t h2
= ar_do_hash(pair
->key
);
688 fprintf(fp
, "miss: hash_eq:%d hints[%d]:%02x hint:%02x\n"
690 " pair->key:%016lx %s\n",
691 h1
== h2
, i
, hints
[i
], hint
,
692 h1
, rb_obj_info(key
), h2
, rb_obj_info(pair
->key
));
694 RB_DEBUG_COUNTER_INC(artable_hint_miss
);
698 RB_DEBUG_COUNTER_INC(artable_hint_notfound
);
699 return RHASH_AR_TABLE_MAX_BOUND
;
703 ar_find_entry(VALUE hash
, st_hash_t hash_value
, st_data_t key
)
705 ar_hint_t hint
= ar_do_hash_hint(hash_value
);
706 return ar_find_entry_hint(hash
, hint
, key
);
710 hash_ar_free_and_clear_table(VALUE hash
)
712 RHASH_AR_TABLE_CLEAR(hash
);
714 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash
) == 0);
715 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash
) == 0);
718 void rb_st_add_direct_with_hash(st_table
*tab
, st_data_t key
, st_data_t value
, st_hash_t hash
); // st.c
720 enum ar_each_key_type
{
727 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
)
729 for (int i
= 0; i
< max
; i
++) {
730 ar_table_pair
*pair
= &ar
->pairs
[i
];
733 case ar_each_key_copy
:
734 dst_keys
[i
] = pair
->key
;
736 case ar_each_key_cmp
:
737 if (dst_keys
[i
] != pair
->key
) return 1;
739 case ar_each_key_insert
:
740 if (UNDEF_P(pair
->key
)) continue; // deleted entry
741 rb_st_add_direct_with_hash(new_tab
, pair
->key
, pair
->val
, hashes
[i
]);
750 ar_force_convert_table(VALUE hash
, const char *file
, int line
)
752 if (RHASH_ST_TABLE_P(hash
)) {
753 return RHASH_ST_TABLE(hash
);
756 ar_table
*ar
= RHASH_AR_TABLE(hash
);
757 st_hash_t hashes
[RHASH_AR_TABLE_MAX_SIZE
];
758 unsigned int bound
, size
;
760 // prepare hash values
762 st_data_t keys
[RHASH_AR_TABLE_MAX_SIZE
];
763 bound
= RHASH_AR_TABLE_BOUND(hash
);
764 size
= RHASH_AR_TABLE_SIZE(hash
);
765 ar_each_key(ar
, bound
, ar_each_key_copy
, keys
, NULL
, NULL
);
767 for (unsigned int i
= 0; i
< bound
; i
++) {
768 // do_hash calls #hash method and it can modify hash object
769 hashes
[i
] = UNDEF_P(keys
[i
]) ? 0 : ar_do_hash(keys
[i
]);
773 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) return RHASH_ST_TABLE(hash
);
774 if (UNLIKELY(RHASH_AR_TABLE_BOUND(hash
) != bound
)) continue;
775 if (UNLIKELY(ar_each_key(ar
, bound
, ar_each_key_cmp
, keys
, NULL
, NULL
))) continue;
780 st_table
*new_tab
= &tab
;
781 st_init_existing_table_with_size(new_tab
, &objhash
, size
);
782 ar_each_key(ar
, bound
, ar_each_key_insert
, NULL
, new_tab
, hashes
);
783 hash_ar_free_and_clear_table(hash
);
784 RHASH_ST_TABLE_SET(hash
, new_tab
);
785 return RHASH_ST_TABLE(hash
);
790 ar_compact_table(VALUE hash
)
792 const unsigned bound
= RHASH_AR_TABLE_BOUND(hash
);
793 const unsigned size
= RHASH_AR_TABLE_SIZE(hash
);
800 ar_table_pair
*pairs
= RHASH_AR_TABLE(hash
)->pairs
;
802 for (i
=0; i
<bound
; i
++) {
803 if (ar_cleared_entry(hash
, i
)) {
805 for (; j
<bound
; j
++) {
806 if (!ar_cleared_entry(hash
, j
)) {
808 ar_hint_set_hint(hash
, i
, (st_hash_t
)ar_hint(hash
, j
));
809 ar_clear_entry(hash
, j
);
814 /* non-empty is not found */
820 HASH_ASSERT(i
<=bound
);
822 RHASH_AR_TABLE_BOUND_SET(hash
, size
);
829 ar_add_direct_with_hash(VALUE hash
, st_data_t key
, st_data_t val
, st_hash_t hash_value
)
831 unsigned bin
= RHASH_AR_TABLE_BOUND(hash
);
833 if (RHASH_AR_TABLE_SIZE(hash
) >= RHASH_AR_TABLE_MAX_SIZE
) {
837 if (UNLIKELY(bin
>= RHASH_AR_TABLE_MAX_BOUND
)) {
838 bin
= ar_compact_table(hash
);
840 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
842 ar_set_entry(hash
, bin
, key
, val
, hash_value
);
843 RHASH_AR_TABLE_BOUND_SET(hash
, bin
+1);
844 RHASH_AR_TABLE_SIZE_INC(hash
);
850 ensure_ar_table(VALUE hash
)
852 if (!RHASH_AR_TABLE_P(hash
)) {
853 rb_raise(rb_eRuntimeError
, "hash representation was changed during iteration");
858 ar_general_foreach(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
860 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
861 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
863 for (i
= 0; i
< bound
; i
++) {
864 if (ar_cleared_entry(hash
, i
)) continue;
866 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
867 st_data_t key
= (st_data_t
)pair
->key
;
868 st_data_t val
= (st_data_t
)pair
->val
;
869 enum st_retval retval
= (*func
)(key
, val
, arg
, 0);
870 ensure_ar_table(hash
);
871 /* pair may be not valid here because of theap */
881 retval
= (*replace
)(&key
, &val
, arg
, TRUE
);
883 // TODO: pair should be same as pair before.
884 pair
= RHASH_AR_TABLE_REF(hash
, i
);
885 pair
->key
= (VALUE
)key
;
886 pair
->val
= (VALUE
)val
;
890 ar_clear_entry(hash
, i
);
891 RHASH_AR_TABLE_SIZE_DEC(hash
);
900 ar_foreach_with_replace(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
902 return ar_general_foreach(hash
, func
, replace
, arg
);
906 st_foreach_callback_func
*func
;
911 apply_functor(st_data_t k
, st_data_t v
, st_data_t d
, int _
)
913 const struct functor
*f
= (void *)d
;
914 return f
->func(k
, v
, f
->arg
);
918 ar_foreach(VALUE hash
, st_foreach_callback_func
*func
, st_data_t arg
)
920 const struct functor f
= { func
, arg
};
921 return ar_general_foreach(hash
, apply_functor
, NULL
, (st_data_t
)&f
);
925 ar_foreach_check(VALUE hash
, st_foreach_check_callback_func
*func
, st_data_t arg
,
928 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
929 unsigned i
, ret
= 0, bound
= RHASH_AR_TABLE_BOUND(hash
);
930 enum st_retval retval
;
935 for (i
= 0; i
< bound
; i
++) {
936 if (ar_cleared_entry(hash
, i
)) continue;
938 pair
= RHASH_AR_TABLE_REF(hash
, i
);
940 hint
= ar_hint(hash
, i
);
942 retval
= (*func
)(key
, pair
->val
, arg
, 0);
943 ensure_ar_table(hash
);
948 pair
= RHASH_AR_TABLE_REF(hash
, i
);
949 if (pair
->key
== never
) break;
950 ret
= ar_find_entry_hint(hash
, hint
, key
);
951 if (ret
== RHASH_AR_TABLE_MAX_BOUND
) {
952 retval
= (*func
)(0, 0, arg
, 1);
962 if (!ar_cleared_entry(hash
, i
)) {
963 ar_clear_entry(hash
, i
);
964 RHASH_AR_TABLE_SIZE_DEC(hash
);
975 ar_update(VALUE hash
, st_data_t key
,
976 st_update_callback_func
*func
, st_data_t arg
)
978 int retval
, existing
;
979 unsigned bin
= RHASH_AR_TABLE_MAX_BOUND
;
980 st_data_t value
= 0, old_key
;
981 st_hash_t hash_value
= ar_do_hash(key
);
983 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
984 // `#hash` changes ar_table -> st_table
988 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
989 bin
= ar_find_entry(hash
, hash_value
, key
);
990 existing
= (bin
!= RHASH_AR_TABLE_MAX_BOUND
) ? TRUE
: FALSE
;
997 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1002 retval
= (*func
)(&key
, &value
, arg
, existing
);
1003 /* pair can be invalid here because of theap */
1004 ensure_ar_table(hash
);
1009 if (ar_add_direct_with_hash(hash
, key
, value
, hash_value
)) {
1014 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1015 if (old_key
!= key
) {
1023 ar_clear_entry(hash
, bin
);
1024 RHASH_AR_TABLE_SIZE_DEC(hash
);
1032 ar_insert(VALUE hash
, st_data_t key
, st_data_t value
)
1034 unsigned bin
= RHASH_AR_TABLE_BOUND(hash
);
1035 st_hash_t hash_value
= ar_do_hash(key
);
1037 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1038 // `#hash` changes ar_table -> st_table
1042 bin
= ar_find_entry(hash
, hash_value
, key
);
1043 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1044 if (RHASH_AR_TABLE_SIZE(hash
) >= RHASH_AR_TABLE_MAX_SIZE
) {
1047 else if (bin
>= RHASH_AR_TABLE_MAX_BOUND
) {
1048 bin
= ar_compact_table(hash
);
1050 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
1052 ar_set_entry(hash
, bin
, key
, value
, hash_value
);
1053 RHASH_AR_TABLE_BOUND_SET(hash
, bin
+1);
1054 RHASH_AR_TABLE_SIZE_INC(hash
);
1058 RHASH_AR_TABLE_REF(hash
, bin
)->val
= value
;
1064 ar_lookup(VALUE hash
, st_data_t key
, st_data_t
*value
)
1066 if (RHASH_AR_TABLE_SIZE(hash
) == 0) {
1070 st_hash_t hash_value
= ar_do_hash(key
);
1071 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1072 // `#hash` changes ar_table -> st_table
1073 return st_lookup(RHASH_ST_TABLE(hash
), key
, value
);
1075 unsigned bin
= ar_find_entry(hash
, hash_value
, key
);
1077 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1081 HASH_ASSERT(bin
< RHASH_AR_TABLE_MAX_BOUND
);
1082 if (value
!= NULL
) {
1083 *value
= RHASH_AR_TABLE_REF(hash
, bin
)->val
;
1091 ar_delete(VALUE hash
, st_data_t
*key
, st_data_t
*value
)
1094 st_hash_t hash_value
= ar_do_hash(*key
);
1096 if (UNLIKELY(!RHASH_AR_TABLE_P(hash
))) {
1097 // `#hash` changes ar_table -> st_table
1098 return st_delete(RHASH_ST_TABLE(hash
), key
, value
);
1101 bin
= ar_find_entry(hash
, hash_value
, *key
);
1103 if (bin
== RHASH_AR_TABLE_MAX_BOUND
) {
1104 if (value
!= 0) *value
= 0;
1109 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, bin
);
1112 ar_clear_entry(hash
, bin
);
1113 RHASH_AR_TABLE_SIZE_DEC(hash
);
1119 ar_shift(VALUE hash
, st_data_t
*key
, st_data_t
*value
)
1121 if (RHASH_AR_TABLE_SIZE(hash
) > 0) {
1122 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1124 for (i
= 0; i
< bound
; i
++) {
1125 if (!ar_cleared_entry(hash
, i
)) {
1126 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
1127 if (value
!= 0) *value
= pair
->val
;
1129 ar_clear_entry(hash
, i
);
1130 RHASH_AR_TABLE_SIZE_DEC(hash
);
1135 if (value
!= NULL
) *value
= 0;
1140 ar_keys(VALUE hash
, st_data_t
*keys
, st_index_t size
)
1142 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1143 st_data_t
*keys_start
= keys
, *keys_end
= keys
+ size
;
1145 for (i
= 0; i
< bound
; i
++) {
1146 if (keys
== keys_end
) {
1150 if (!ar_cleared_entry(hash
, i
)) {
1151 *keys
++ = RHASH_AR_TABLE_REF(hash
, i
)->key
;
1156 return keys
- keys_start
;
1160 ar_values(VALUE hash
, st_data_t
*values
, st_index_t size
)
1162 unsigned i
, bound
= RHASH_AR_TABLE_BOUND(hash
);
1163 st_data_t
*values_start
= values
, *values_end
= values
+ size
;
1165 for (i
= 0; i
< bound
; i
++) {
1166 if (values
== values_end
) {
1170 if (!ar_cleared_entry(hash
, i
)) {
1171 *values
++ = RHASH_AR_TABLE_REF(hash
, i
)->val
;
1176 return values
- values_start
;
1180 ar_copy(VALUE hash1
, VALUE hash2
)
1182 ar_table
*old_tab
= RHASH_AR_TABLE(hash2
);
1183 ar_table
*new_tab
= RHASH_AR_TABLE(hash1
);
1185 *new_tab
= *old_tab
;
1186 RHASH_AR_TABLE(hash1
)->ar_hint
.word
= RHASH_AR_TABLE(hash2
)->ar_hint
.word
;
1187 RHASH_AR_TABLE_BOUND_SET(hash1
, RHASH_AR_TABLE_BOUND(hash2
));
1188 RHASH_AR_TABLE_SIZE_SET(hash1
, RHASH_AR_TABLE_SIZE(hash2
));
1190 rb_gc_writebarrier_remember(hash1
);
1196 ar_clear(VALUE hash
)
1198 if (RHASH_AR_TABLE(hash
) != NULL
) {
1199 RHASH_AR_TABLE_SIZE_SET(hash
, 0);
1200 RHASH_AR_TABLE_BOUND_SET(hash
, 0);
1203 HASH_ASSERT(RHASH_AR_TABLE_SIZE(hash
) == 0);
1204 HASH_ASSERT(RHASH_AR_TABLE_BOUND(hash
) == 0);
1209 hash_st_free(VALUE hash
)
1211 HASH_ASSERT(RHASH_ST_TABLE_P(hash
));
1213 st_table
*tab
= RHASH_ST_TABLE(hash
);
1216 xfree(tab
->entries
);
1220 hash_st_free_and_clear_table(VALUE hash
)
1224 RHASH_ST_CLEAR(hash
);
1228 rb_hash_free(VALUE hash
)
1230 if (RHASH_ST_TABLE_P(hash
)) {
1235 typedef int st_foreach_func(st_data_t
, st_data_t
, st_data_t
);
1237 struct foreach_safe_arg
{
1239 st_foreach_func
*func
;
1244 foreach_safe_i(st_data_t key
, st_data_t value
, st_data_t args
, int error
)
1247 struct foreach_safe_arg
*arg
= (void *)args
;
1249 if (error
) return ST_STOP
;
1250 status
= (*arg
->func
)(key
, value
, arg
->arg
);
1251 if (status
== ST_CONTINUE
) {
1258 st_foreach_safe(st_table
*table
, st_foreach_func
*func
, st_data_t a
)
1260 struct foreach_safe_arg arg
;
1263 arg
.func
= (st_foreach_func
*)func
;
1265 if (st_foreach_check(table
, foreach_safe_i
, (st_data_t
)&arg
, 0)) {
1266 rb_raise(rb_eRuntimeError
, "hash modified during iteration");
1270 typedef int rb_foreach_func(VALUE
, VALUE
, VALUE
);
1272 struct hash_foreach_arg
{
1274 rb_foreach_func
*func
;
1279 hash_iter_status_check(int status
)
1294 hash_ar_foreach_iter(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
1296 struct hash_foreach_arg
*arg
= (struct hash_foreach_arg
*)argp
;
1298 if (error
) return ST_STOP
;
1300 int status
= (*arg
->func
)((VALUE
)key
, (VALUE
)value
, arg
->arg
);
1301 /* TODO: rehash check? rb_raise(rb_eRuntimeError, "rehash occurred during iteration"); */
1303 return hash_iter_status_check(status
);
1307 hash_foreach_iter(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
1309 struct hash_foreach_arg
*arg
= (struct hash_foreach_arg
*)argp
;
1311 if (error
) return ST_STOP
;
1313 st_table
*tbl
= RHASH_ST_TABLE(arg
->hash
);
1314 int status
= (*arg
->func
)((VALUE
)key
, (VALUE
)value
, arg
->arg
);
1316 if (RHASH_ST_TABLE(arg
->hash
) != tbl
) {
1317 rb_raise(rb_eRuntimeError
, "rehash occurred during iteration");
1320 return hash_iter_status_check(status
);
1323 static unsigned long
1324 iter_lev_in_ivar(VALUE hash
)
1326 VALUE levval
= rb_ivar_get(hash
, id_hash_iter_lev
);
1327 HASH_ASSERT(FIXNUM_P(levval
));
1328 long lev
= FIX2LONG(levval
);
1329 HASH_ASSERT(lev
>= 0);
1330 return (unsigned long)lev
;
1333 void rb_ivar_set_internal(VALUE obj
, ID id
, VALUE val
);
1336 iter_lev_in_ivar_set(VALUE hash
, unsigned long lev
)
1338 HASH_ASSERT(lev
>= RHASH_LEV_MAX
);
1339 HASH_ASSERT(POSFIXABLE(lev
)); /* POSFIXABLE means fitting to long */
1340 rb_ivar_set_internal(hash
, id_hash_iter_lev
, LONG2FIX((long)lev
));
1343 static inline unsigned long
1344 iter_lev_in_flags(VALUE hash
)
1346 return (unsigned long)((RBASIC(hash
)->flags
>> RHASH_LEV_SHIFT
) & RHASH_LEV_MAX
);
1350 iter_lev_in_flags_set(VALUE hash
, unsigned long lev
)
1352 HASH_ASSERT(lev
<= RHASH_LEV_MAX
);
1353 RBASIC(hash
)->flags
= ((RBASIC(hash
)->flags
& ~RHASH_LEV_MASK
) | ((VALUE
)lev
<< RHASH_LEV_SHIFT
));
1357 hash_iterating_p(VALUE hash
)
1359 return iter_lev_in_flags(hash
) > 0;
1363 hash_iter_lev_inc(VALUE hash
)
1365 unsigned long lev
= iter_lev_in_flags(hash
);
1366 if (lev
== RHASH_LEV_MAX
) {
1367 lev
= iter_lev_in_ivar(hash
) + 1;
1368 if (!POSFIXABLE(lev
)) { /* paranoiac check */
1369 rb_raise(rb_eRuntimeError
, "too much nested iterations");
1374 iter_lev_in_flags_set(hash
, lev
);
1375 if (lev
< RHASH_LEV_MAX
) return;
1377 iter_lev_in_ivar_set(hash
, lev
);
1381 hash_iter_lev_dec(VALUE hash
)
1383 unsigned long lev
= iter_lev_in_flags(hash
);
1384 if (lev
== RHASH_LEV_MAX
) {
1385 lev
= iter_lev_in_ivar(hash
);
1386 if (lev
> RHASH_LEV_MAX
) {
1387 iter_lev_in_ivar_set(hash
, lev
-1);
1390 rb_attr_delete(hash
, id_hash_iter_lev
);
1392 else if (lev
== 0) {
1393 rb_raise(rb_eRuntimeError
, "iteration level underflow");
1395 iter_lev_in_flags_set(hash
, lev
- 1);
1399 hash_foreach_ensure(VALUE hash
)
1401 hash_iter_lev_dec(hash
);
1406 rb_hash_stlike_foreach(VALUE hash
, st_foreach_callback_func
*func
, st_data_t arg
)
1408 if (RHASH_AR_TABLE_P(hash
)) {
1409 return ar_foreach(hash
, func
, arg
);
1412 return st_foreach(RHASH_ST_TABLE(hash
), func
, arg
);
1417 rb_hash_stlike_foreach_with_replace(VALUE hash
, st_foreach_check_callback_func
*func
, st_update_callback_func
*replace
, st_data_t arg
)
1419 if (RHASH_AR_TABLE_P(hash
)) {
1420 return ar_foreach_with_replace(hash
, func
, replace
, arg
);
1423 return st_foreach_with_replace(RHASH_ST_TABLE(hash
), func
, replace
, arg
);
1428 hash_foreach_call(VALUE arg
)
1430 VALUE hash
= ((struct hash_foreach_arg
*)arg
)->hash
;
1432 if (RHASH_AR_TABLE_P(hash
)) {
1433 ret
= ar_foreach_check(hash
, hash_ar_foreach_iter
,
1434 (st_data_t
)arg
, (st_data_t
)Qundef
);
1436 else if (RHASH_ST_TABLE_P(hash
)) {
1437 ret
= st_foreach_check(RHASH_ST_TABLE(hash
), hash_foreach_iter
,
1438 (st_data_t
)arg
, (st_data_t
)Qundef
);
1441 rb_raise(rb_eRuntimeError
, "ret: %d, hash modified during iteration", ret
);
1447 rb_hash_foreach(VALUE hash
, rb_foreach_func
*func
, VALUE farg
)
1449 struct hash_foreach_arg arg
;
1451 if (RHASH_TABLE_EMPTY_P(hash
))
1454 arg
.func
= (rb_foreach_func
*)func
;
1456 if (RB_OBJ_FROZEN(hash
)) {
1457 hash_foreach_call((VALUE
)&arg
);
1460 hash_iter_lev_inc(hash
);
1461 rb_ensure(hash_foreach_call
, (VALUE
)&arg
, hash_foreach_ensure
, hash
);
1466 void rb_st_compact_table(st_table
*tab
);
1469 compact_after_delete(VALUE hash
)
1471 if (!hash_iterating_p(hash
) && RHASH_ST_TABLE_P(hash
)) {
1472 rb_st_compact_table(RHASH_ST_TABLE(hash
));
1477 hash_alloc_flags(VALUE klass
, VALUE flags
, VALUE ifnone
, bool st
)
1479 const VALUE wb
= (RGENGC_WB_PROTECTED_HASH
? FL_WB_PROTECTED
: 0);
1480 const size_t size
= sizeof(struct RHash
) + (st
? sizeof(st_table
) : sizeof(ar_table
));
1482 NEWOBJ_OF(hash
, struct RHash
, klass
, T_HASH
| wb
| flags
, size
, 0);
1484 RHASH_SET_IFNONE((VALUE
)hash
, ifnone
);
1490 hash_alloc(VALUE klass
)
1492 /* Allocate to be able to fit both st_table and ar_table. */
1493 return hash_alloc_flags(klass
, 0, Qnil
, sizeof(st_table
) > sizeof(ar_table
));
1497 empty_hash_alloc(VALUE klass
)
1499 RUBY_DTRACE_CREATE_HOOK(HASH
, 0);
1501 return hash_alloc(klass
);
1507 return hash_alloc(rb_cHash
);
1511 copy_compare_by_id(VALUE hash
, VALUE basis
)
1513 if (rb_hash_compare_by_id_p(basis
)) {
1514 return rb_hash_compare_by_id(hash
);
1520 rb_hash_new_with_size(st_index_t size
)
1522 bool st
= size
> RHASH_AR_TABLE_MAX_SIZE
;
1523 VALUE ret
= hash_alloc_flags(rb_cHash
, 0, Qnil
, st
);
1526 hash_st_table_init(ret
, &objhash
, size
);
1533 rb_hash_new_capa(long capa
)
1535 return rb_hash_new_with_size((st_index_t
)capa
);
1539 hash_copy(VALUE ret
, VALUE hash
)
1541 if (RHASH_AR_TABLE_P(hash
)) {
1542 if (RHASH_AR_TABLE_P(ret
)) {
1546 st_table
*tab
= RHASH_ST_TABLE(ret
);
1547 st_init_existing_table_with_size(tab
, &objhash
, RHASH_AR_TABLE_SIZE(hash
));
1549 int bound
= RHASH_AR_TABLE_BOUND(hash
);
1550 for (int i
= 0; i
< bound
; i
++) {
1551 if (ar_cleared_entry(hash
, i
)) continue;
1553 ar_table_pair
*pair
= RHASH_AR_TABLE_REF(hash
, i
);
1554 st_add_direct(tab
, pair
->key
, pair
->val
);
1555 RB_OBJ_WRITTEN(ret
, Qundef
, pair
->key
);
1556 RB_OBJ_WRITTEN(ret
, Qundef
, pair
->val
);
1561 HASH_ASSERT(sizeof(st_table
) <= sizeof(ar_table
));
1563 RHASH_SET_ST_FLAG(ret
);
1564 st_replace(RHASH_ST_TABLE(ret
), RHASH_ST_TABLE(hash
));
1566 rb_gc_writebarrier_remember(ret
);
1572 hash_dup_with_compare_by_id(VALUE hash
)
1574 VALUE dup
= hash_alloc_flags(rb_cHash
, 0, Qnil
, RHASH_ST_TABLE_P(hash
));
1575 if (RHASH_ST_TABLE_P(hash
)) {
1576 RHASH_SET_ST_FLAG(dup
);
1579 RHASH_UNSET_ST_FLAG(dup
);
1582 return hash_copy(dup
, hash
);
1586 hash_dup(VALUE hash
, VALUE klass
, VALUE flags
)
1588 return hash_copy(hash_alloc_flags(klass
, flags
, RHASH_IFNONE(hash
), !RHASH_EMPTY_P(hash
) && RHASH_ST_TABLE_P(hash
)),
1593 rb_hash_dup(VALUE hash
)
1595 const VALUE flags
= RBASIC(hash
)->flags
;
1596 VALUE ret
= hash_dup(hash
, rb_obj_class(hash
),
1597 flags
& (FL_EXIVAR
|RHASH_PROC_DEFAULT
));
1598 if (flags
& FL_EXIVAR
)
1599 rb_copy_generic_ivar(ret
, hash
);
1604 rb_hash_resurrect(VALUE hash
)
1606 VALUE ret
= hash_dup(hash
, rb_cHash
, 0);
1611 rb_hash_modify_check(VALUE hash
)
1613 rb_check_frozen(hash
);
1617 rb_hash_tbl_raw(VALUE hash
, const char *file
, int line
)
1619 return ar_force_convert_table(hash
, file
, line
);
1623 rb_hash_tbl(VALUE hash
, const char *file
, int line
)
1625 OBJ_WB_UNPROTECT(hash
);
1626 return rb_hash_tbl_raw(hash
, file
, line
);
1630 rb_hash_modify(VALUE hash
)
1632 rb_hash_modify_check(hash
);
1635 NORETURN(static void no_new_key(void));
1639 rb_raise(rb_eRuntimeError
, "can't add a new key into hash during iteration");
1642 struct update_callback_arg
{
1647 #define NOINSERT_UPDATE_CALLBACK(func) \
1649 func##_noinsert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1651 if (!existing) no_new_key(); \
1652 return func(key, val, (struct update_arg *)arg, existing); \
1656 func##_insert(st_data_t *key, st_data_t *val, st_data_t arg, int existing) \
1658 return func(key, val, (struct update_arg *)arg, existing); \
1663 st_update_callback_func
*func
;
1669 typedef int (*tbl_update_func
)(st_data_t
*, st_data_t
*, st_data_t
, int);
1672 rb_hash_stlike_update(VALUE hash
, st_data_t key
, st_update_callback_func
*func
, st_data_t arg
)
1674 if (RHASH_AR_TABLE_P(hash
)) {
1675 int result
= ar_update(hash
, key
, func
, arg
);
1677 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
1684 return st_update(RHASH_ST_TABLE(hash
), key
, func
, arg
);
1688 tbl_update_modify(st_data_t
*key
, st_data_t
*val
, st_data_t arg
, int existing
)
1690 struct update_arg
*p
= (struct update_arg
*)arg
;
1691 st_data_t old_key
= *key
;
1692 st_data_t old_value
= *val
;
1693 VALUE hash
= p
->hash
;
1694 int ret
= (p
->func
)(key
, val
, arg
, existing
);
1699 if (!existing
|| *key
!= old_key
|| *val
!= old_value
) {
1700 rb_hash_modify(hash
);
1707 rb_hash_modify(hash
);
1715 tbl_update(VALUE hash
, VALUE key
, tbl_update_func func
, st_data_t optional_arg
)
1717 struct update_arg arg
= {
1718 .arg
= optional_arg
,
1722 .value
= (VALUE
)optional_arg
,
1725 int ret
= rb_hash_stlike_update(hash
, key
, tbl_update_modify
, (st_data_t
)&arg
);
1728 RB_OBJ_WRITTEN(hash
, Qundef
, arg
.key
);
1729 RB_OBJ_WRITTEN(hash
, Qundef
, arg
.value
);
1734 #define UPDATE_CALLBACK(iter_p, func) ((iter_p) ? func##_noinsert : func##_insert)
1736 #define RHASH_UPDATE_ITER(h, iter_p, key, func, a) do { \
1737 tbl_update((h), (key), UPDATE_CALLBACK(iter_p, func), (st_data_t)(a)); \
1740 #define RHASH_UPDATE(hash, key, func, arg) \
1741 RHASH_UPDATE_ITER(hash, hash_iterating_p(hash), key, func, arg)
1744 set_proc_default(VALUE hash
, VALUE proc
)
1746 if (rb_proc_lambda_p(proc
)) {
1747 int n
= rb_proc_arity(proc
);
1749 if (n
!= 2 && (n
>= 0 || n
< -3)) {
1750 if (n
< 0) n
= -n
-1;
1751 rb_raise(rb_eTypeError
, "default_proc takes two arguments (2 for %d)", n
);
1755 FL_SET_RAW(hash
, RHASH_PROC_DEFAULT
);
1756 RHASH_SET_IFNONE(hash
, proc
);
1760 rb_hash_init(rb_execution_context_t
*ec
, VALUE hash
, VALUE capa_value
, VALUE ifnone_unset
, VALUE ifnone
, VALUE block
)
1762 rb_hash_modify(hash
);
1764 if (capa_value
!= INT2FIX(0)) {
1765 long capa
= NUM2LONG(capa_value
);
1766 if (capa
> 0 && RHASH_SIZE(hash
) == 0 && RHASH_AR_TABLE_P(hash
)) {
1767 hash_st_table_init(hash
, &objhash
, capa
);
1771 if (!NIL_P(block
)) {
1772 if (ifnone_unset
!= Qtrue
) {
1773 rb_check_arity(1, 0, 0);
1776 SET_PROC_DEFAULT(hash
, block
);
1780 RHASH_SET_IFNONE(hash
, ifnone_unset
== Qtrue
? Qnil
: ifnone
);
1787 static VALUE
rb_hash_to_a(VALUE hash
);
1791 * Hash[] -> new_empty_hash
1792 * Hash[hash] -> new_hash
1793 * Hash[ [*2_element_arrays] ] -> new_hash
1794 * Hash[*objects] -> new_hash
1796 * Returns a new +Hash+ object populated with the given objects, if any.
1799 * With no argument, returns a new empty +Hash+.
1801 * When the single given argument is a +Hash+, returns a new +Hash+
1802 * populated with the entries from the given +Hash+, excluding the
1803 * default value or proc.
1805 * h = {foo: 0, bar: 1, baz: 2}
1806 * Hash[h] # => {:foo=>0, :bar=>1, :baz=>2}
1808 * When the single given argument is an Array of 2-element Arrays,
1809 * returns a new +Hash+ object wherein each 2-element array forms a
1812 * Hash[ [ [:foo, 0], [:bar, 1] ] ] # => {:foo=>0, :bar=>1}
1814 * When the argument count is an even number;
1815 * returns a new +Hash+ object wherein each successive pair of arguments
1816 * has become a key-value entry:
1818 * Hash[:foo, 0, :bar, 1] # => {:foo=>0, :bar=>1}
1820 * Raises an exception if the argument list does not conform to any
1825 rb_hash_s_create(int argc
, VALUE
*argv
, VALUE klass
)
1830 tmp
= rb_hash_s_try_convert(Qnil
, argv
[0]);
1832 if (!RHASH_EMPTY_P(tmp
) && rb_hash_compare_by_id_p(tmp
)) {
1833 /* hash_copy for non-empty hash will copy compare_by_identity
1834 flag, but we don't want it copied. Work around by
1835 converting hash to flattened array and using that. */
1836 tmp
= rb_hash_to_a(tmp
);
1839 hash
= hash_alloc(klass
);
1840 if (!RHASH_EMPTY_P(tmp
))
1841 hash_copy(hash
, tmp
);
1846 tmp
= rb_check_array_type(argv
[0]);
1852 hash
= hash_alloc(klass
);
1853 for (i
= 0; i
< RARRAY_LEN(tmp
); ++i
) {
1854 VALUE e
= RARRAY_AREF(tmp
, i
);
1855 VALUE v
= rb_check_array_type(e
);
1856 VALUE key
, val
= Qnil
;
1859 rb_raise(rb_eArgError
, "wrong element type %s at %ld (expected array)",
1860 rb_builtin_class_name(e
), i
);
1862 switch (RARRAY_LEN(v
)) {
1864 rb_raise(rb_eArgError
, "invalid number of elements (%ld for 1..2)",
1867 val
= RARRAY_AREF(v
, 1);
1869 key
= RARRAY_AREF(v
, 0);
1870 rb_hash_aset(hash
, key
, val
);
1876 if (argc
% 2 != 0) {
1877 rb_raise(rb_eArgError
, "odd number of arguments for Hash");
1880 hash
= hash_alloc(klass
);
1881 rb_hash_bulk_insert(argc
, argv
, hash
);
1887 rb_to_hash_type(VALUE hash
)
1889 return rb_convert_type_with_id(hash
, T_HASH
, "Hash", idTo_hash
);
1891 #define to_hash rb_to_hash_type
1894 rb_check_hash_type(VALUE hash
)
1896 return rb_check_convert_type_with_id(hash
, T_HASH
, "Hash", idTo_hash
);
1901 * Hash.try_convert(obj) -> obj, new_hash, or nil
1903 * If +obj+ is a +Hash+ object, returns +obj+.
1905 * Otherwise if +obj+ responds to <tt>:to_hash</tt>,
1906 * calls <tt>obj.to_hash</tt> and returns the result.
1908 * Returns +nil+ if +obj+ does not respond to <tt>:to_hash</tt>
1910 * Raises an exception unless <tt>obj.to_hash</tt> returns a +Hash+ object.
1913 rb_hash_s_try_convert(VALUE dummy
, VALUE hash
)
1915 return rb_check_hash_type(hash
);
1920 * Hash.ruby2_keywords_hash?(hash) -> true or false
1922 * Checks if a given hash is flagged by Module#ruby2_keywords (or
1923 * Proc#ruby2_keywords).
1924 * This method is not for casual use; debugging, researching, and
1925 * some truly necessary cases like serialization of arguments.
1927 * ruby2_keywords def foo(*args)
1928 * Hash.ruby2_keywords_hash?(args.last)
1930 * foo(k: 1) #=> true
1931 * foo({k: 1}) #=> false
1934 rb_hash_s_ruby2_keywords_hash_p(VALUE dummy
, VALUE hash
)
1936 Check_Type(hash
, T_HASH
);
1937 return RBOOL(RHASH(hash
)->basic
.flags
& RHASH_PASS_AS_KEYWORDS
);
1942 * Hash.ruby2_keywords_hash(hash) -> hash
1944 * Duplicates a given hash and adds a ruby2_keywords flag.
1945 * This method is not for casual use; debugging, researching, and
1946 * some truly necessary cases like deserialization of arguments.
1949 * h = Hash.ruby2_keywords_hash(h)
1953 * foo(*[h]) #=> 1 with neither a warning or an error
1956 rb_hash_s_ruby2_keywords_hash(VALUE dummy
, VALUE hash
)
1958 Check_Type(hash
, T_HASH
);
1959 VALUE tmp
= rb_hash_dup(hash
);
1960 if (RHASH_EMPTY_P(hash
) && rb_hash_compare_by_id_p(hash
)) {
1961 rb_hash_compare_by_id(tmp
);
1963 RHASH(tmp
)->basic
.flags
|= RHASH_PASS_AS_KEYWORDS
;
1973 rb_hash_rehash_i(VALUE key
, VALUE value
, VALUE arg
)
1975 if (RHASH_AR_TABLE_P(arg
)) {
1976 ar_insert(arg
, (st_data_t
)key
, (st_data_t
)value
);
1979 st_insert(RHASH_ST_TABLE(arg
), (st_data_t
)key
, (st_data_t
)value
);
1986 * hash.rehash -> self
1988 * Rebuilds the hash table by recomputing the hash index for each key;
1989 * returns <tt>self</tt>.
1991 * The hash table becomes invalid if the hash value of a key
1992 * has changed after the entry was created.
1993 * See {Modifying an Active Hash Key}[rdoc-ref:Hash@Modifying+an+Active+Hash+Key].
1997 rb_hash_rehash(VALUE hash
)
2002 if (hash_iterating_p(hash
)) {
2003 rb_raise(rb_eRuntimeError
, "rehash during iteration");
2005 rb_hash_modify_check(hash
);
2006 if (RHASH_AR_TABLE_P(hash
)) {
2007 tmp
= hash_alloc(0);
2008 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
2010 hash_ar_free_and_clear_table(hash
);
2013 else if (RHASH_ST_TABLE_P(hash
)) {
2014 st_table
*old_tab
= RHASH_ST_TABLE(hash
);
2015 tmp
= hash_alloc(0);
2017 hash_st_table_init(tmp
, old_tab
->type
, old_tab
->num_entries
);
2018 tbl
= RHASH_ST_TABLE(tmp
);
2020 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
2023 RHASH_ST_TABLE_SET(hash
, tbl
);
2024 RHASH_ST_CLEAR(tmp
);
2031 call_default_proc(VALUE proc
, VALUE hash
, VALUE key
)
2033 VALUE args
[2] = {hash
, key
};
2034 return rb_proc_call_with_block(proc
, 2, args
, Qnil
);
2038 rb_hash_default_unredefined(VALUE hash
)
2040 VALUE klass
= RBASIC_CLASS(hash
);
2041 if (LIKELY(klass
== rb_cHash
)) {
2042 return !!BASIC_OP_UNREDEFINED_P(BOP_DEFAULT
, HASH_REDEFINED_OP_FLAG
);
2045 return LIKELY(rb_method_basic_definition_p(klass
, id_default
));
2050 rb_hash_default_value(VALUE hash
, VALUE key
)
2052 RUBY_ASSERT(RB_TYPE_P(hash
, T_HASH
));
2054 if (LIKELY(rb_hash_default_unredefined(hash
))) {
2055 VALUE ifnone
= RHASH_IFNONE(hash
);
2056 if (LIKELY(!FL_TEST_RAW(hash
, RHASH_PROC_DEFAULT
))) return ifnone
;
2057 if (UNDEF_P(key
)) return Qnil
;
2058 return call_default_proc(ifnone
, hash
, key
);
2061 return rb_funcall(hash
, id_default
, 1, key
);
2066 hash_stlike_lookup(VALUE hash
, st_data_t key
, st_data_t
*pval
)
2070 if (RHASH_AR_TABLE_P(hash
)) {
2071 return ar_lookup(hash
, key
, pval
);
2074 extern st_index_t
rb_iseq_cdhash_hash(VALUE
);
2075 RUBY_ASSERT(RHASH_ST_TABLE(hash
)->type
->hash
== rb_any_hash
||
2076 RHASH_ST_TABLE(hash
)->type
->hash
== rb_ident_hash
||
2077 RHASH_ST_TABLE(hash
)->type
->hash
== rb_iseq_cdhash_hash
);
2078 return st_lookup(RHASH_ST_TABLE(hash
), key
, pval
);
2083 rb_hash_stlike_lookup(VALUE hash
, st_data_t key
, st_data_t
*pval
)
2085 return hash_stlike_lookup(hash
, key
, pval
);
2090 * hash[key] -> value
2092 * Returns the value associated with the given +key+, if found:
2093 * h = {foo: 0, bar: 1, baz: 2}
2096 * If +key+ is not found, returns a default value
2097 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2098 * h = {foo: 0, bar: 1, baz: 2}
2099 * h[:nosuch] # => nil
2103 rb_hash_aref(VALUE hash
, VALUE key
)
2107 if (hash_stlike_lookup(hash
, key
, &val
)) {
2111 return rb_hash_default_value(hash
, key
);
2116 rb_hash_lookup2(VALUE hash
, VALUE key
, VALUE def
)
2120 if (hash_stlike_lookup(hash
, key
, &val
)) {
2124 return def
; /* without Hash#default */
2129 rb_hash_lookup(VALUE hash
, VALUE key
)
2131 return rb_hash_lookup2(hash
, key
, Qnil
);
2136 * hash.fetch(key) -> object
2137 * hash.fetch(key, default_value) -> object
2138 * hash.fetch(key) {|key| ... } -> object
2140 * Returns the value for the given +key+, if found.
2141 * h = {foo: 0, bar: 1, baz: 2}
2142 * h.fetch(:bar) # => 1
2144 * If +key+ is not found and no block was given,
2145 * returns +default_value+:
2146 * {}.fetch(:nosuch, :default) # => :default
2148 * If +key+ is not found and a block was given,
2149 * yields +key+ to the block and returns the block's return value:
2150 * {}.fetch(:nosuch) {|key| "No key #{key}"} # => "No key nosuch"
2152 * Raises KeyError if neither +default_value+ nor a block was given.
2154 * Note that this method does not use the values of either #default or #default_proc.
2158 rb_hash_fetch_m(int argc
, VALUE
*argv
, VALUE hash
)
2164 rb_check_arity(argc
, 1, 2);
2167 block_given
= rb_block_given_p();
2168 if (block_given
&& argc
== 2) {
2169 rb_warn("block supersedes default value argument");
2172 if (hash_stlike_lookup(hash
, key
, &val
)) {
2177 return rb_yield(key
);
2179 else if (argc
== 1) {
2180 VALUE desc
= rb_protect(rb_inspect
, key
, 0);
2182 desc
= rb_any_to_s(key
);
2184 desc
= rb_str_ellipsize(desc
, 65);
2185 rb_key_err_raise(rb_sprintf("key not found: %"PRIsVALUE
, desc
), hash
, key
);
2194 rb_hash_fetch(VALUE hash
, VALUE key
)
2196 return rb_hash_fetch_m(1, &key
, hash
);
2201 * hash.default -> object
2202 * hash.default(key) -> object
2204 * Returns the default value for the given +key+.
2205 * The returned value will be determined either by the default proc or by the default value.
2206 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2208 * With no argument, returns the current default value:
2210 * h.default # => nil
2212 * If +key+ is given, returns the default value for +key+,
2213 * regardless of whether that key exists:
2214 * h = Hash.new { |hash, key| hash[key] = "No key #{key}"}
2216 * h.default(:foo) # => "No key foo"
2220 rb_hash_default(int argc
, VALUE
*argv
, VALUE hash
)
2224 rb_check_arity(argc
, 0, 1);
2225 ifnone
= RHASH_IFNONE(hash
);
2226 if (FL_TEST(hash
, RHASH_PROC_DEFAULT
)) {
2227 if (argc
== 0) return Qnil
;
2228 return call_default_proc(ifnone
, hash
, argv
[0]);
2235 * hash.default = value -> object
2237 * Sets the default value to +value+; returns +value+:
2239 * h.default # => nil
2240 * h.default = false # => false
2241 * h.default # => false
2243 * See {Default Values}[rdoc-ref:Hash@Default+Values].
2247 rb_hash_set_default(VALUE hash
, VALUE ifnone
)
2249 rb_hash_modify_check(hash
);
2250 SET_DEFAULT(hash
, ifnone
);
2256 * hash.default_proc -> proc or nil
2258 * Returns the default proc for +self+
2259 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2261 * h.default_proc # => nil
2262 * h.default_proc = proc {|hash, key| "Default value for #{key}" }
2263 * h.default_proc.class # => Proc
2267 rb_hash_default_proc(VALUE hash
)
2269 if (FL_TEST(hash
, RHASH_PROC_DEFAULT
)) {
2270 return RHASH_IFNONE(hash
);
2277 * hash.default_proc = proc -> proc
2279 * Sets the default proc for +self+ to +proc+
2280 * (see {Default Values}[rdoc-ref:Hash@Default+Values]):
2282 * h.default_proc # => nil
2283 * h.default_proc = proc { |hash, key| "Default value for #{key}" }
2284 * h.default_proc.class # => Proc
2285 * h.default_proc = nil
2286 * h.default_proc # => nil
2290 rb_hash_set_default_proc(VALUE hash
, VALUE proc
)
2294 rb_hash_modify_check(hash
);
2296 SET_DEFAULT(hash
, proc
);
2299 b
= rb_check_convert_type_with_id(proc
, T_DATA
, "Proc", idTo_proc
);
2300 if (NIL_P(b
) || !rb_obj_is_proc(b
)) {
2301 rb_raise(rb_eTypeError
,
2302 "wrong default_proc type %s (expected Proc)",
2303 rb_obj_classname(proc
));
2306 SET_PROC_DEFAULT(hash
, proc
);
2311 key_i(VALUE key
, VALUE value
, VALUE arg
)
2313 VALUE
*args
= (VALUE
*)arg
;
2315 if (rb_equal(value
, args
[0])) {
2324 * hash.key(value) -> key or nil
2326 * Returns the key for the first-found entry with the given +value+
2327 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2328 * h = {foo: 0, bar: 2, baz: 2}
2329 * h.key(0) # => :foo
2330 * h.key(2) # => :bar
2332 * Returns +nil+ if no such value is found.
2336 rb_hash_key(VALUE hash
, VALUE value
)
2343 rb_hash_foreach(hash
, key_i
, (VALUE
)args
);
2349 rb_hash_stlike_delete(VALUE hash
, st_data_t
*pkey
, st_data_t
*pval
)
2351 if (RHASH_AR_TABLE_P(hash
)) {
2352 return ar_delete(hash
, pkey
, pval
);
2355 return st_delete(RHASH_ST_TABLE(hash
), pkey
, pval
);
2360 * delete a specified entry by a given key.
2361 * if there is the corresponding entry, return a value of the entry.
2362 * if there is no corresponding entry, return Qundef.
2365 rb_hash_delete_entry(VALUE hash
, VALUE key
)
2367 st_data_t ktmp
= (st_data_t
)key
, val
;
2369 if (rb_hash_stlike_delete(hash
, &ktmp
, &val
)) {
2378 * delete a specified entry by a given key.
2379 * if there is the corresponding entry, return a value of the entry.
2380 * if there is no corresponding entry, return Qnil.
2383 rb_hash_delete(VALUE hash
, VALUE key
)
2385 VALUE deleted_value
= rb_hash_delete_entry(hash
, key
);
2387 if (!UNDEF_P(deleted_value
)) { /* likely pass */
2388 return deleted_value
;
2397 * hash.delete(key) -> value or nil
2398 * hash.delete(key) {|key| ... } -> object
2400 * Deletes the entry for the given +key+ and returns its associated value.
2402 * If no block is given and +key+ is found, deletes the entry and returns the associated value:
2403 * h = {foo: 0, bar: 1, baz: 2}
2404 * h.delete(:bar) # => 1
2405 * h # => {:foo=>0, :baz=>2}
2407 * If no block given and +key+ is not found, returns +nil+.
2409 * If a block is given and +key+ is found, ignores the block,
2410 * deletes the entry, and returns the associated value:
2411 * h = {foo: 0, bar: 1, baz: 2}
2412 * h.delete(:baz) { |key| raise 'Will never happen'} # => 2
2413 * h # => {:foo=>0, :bar=>1}
2415 * If a block is given and +key+ is not found,
2416 * calls the block and returns the block's return value:
2417 * h = {foo: 0, bar: 1, baz: 2}
2418 * h.delete(:nosuch) { |key| "Key #{key} not found" } # => "Key nosuch not found"
2419 * h # => {:foo=>0, :bar=>1, :baz=>2}
2423 rb_hash_delete_m(VALUE hash
, VALUE key
)
2427 rb_hash_modify_check(hash
);
2428 val
= rb_hash_delete_entry(hash
, key
);
2430 if (!UNDEF_P(val
)) {
2431 compact_after_delete(hash
);
2435 if (rb_block_given_p()) {
2436 return rb_yield(key
);
2450 shift_i_safe(VALUE key
, VALUE value
, VALUE arg
)
2452 struct shift_var
*var
= (struct shift_var
*)arg
;
2461 * hash.shift -> [key, value] or nil
2463 * Removes the first hash entry
2464 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]);
2465 * returns a 2-element Array containing the removed key and value:
2466 * h = {foo: 0, bar: 1, baz: 2}
2467 * h.shift # => [:foo, 0]
2468 * h # => {:bar=>1, :baz=>2}
2470 * Returns nil if the hash is empty.
2474 rb_hash_shift(VALUE hash
)
2476 struct shift_var var
;
2478 rb_hash_modify_check(hash
);
2479 if (RHASH_AR_TABLE_P(hash
)) {
2481 if (!hash_iterating_p(hash
)) {
2482 if (ar_shift(hash
, &var
.key
, &var
.val
)) {
2483 return rb_assoc_new(var
.key
, var
.val
);
2487 rb_hash_foreach(hash
, shift_i_safe
, (VALUE
)&var
);
2488 if (!UNDEF_P(var
.key
)) {
2489 rb_hash_delete_entry(hash
, var
.key
);
2490 return rb_assoc_new(var
.key
, var
.val
);
2494 if (RHASH_ST_TABLE_P(hash
)) {
2496 if (!hash_iterating_p(hash
)) {
2497 if (st_shift(RHASH_ST_TABLE(hash
), &var
.key
, &var
.val
)) {
2498 return rb_assoc_new(var
.key
, var
.val
);
2502 rb_hash_foreach(hash
, shift_i_safe
, (VALUE
)&var
);
2503 if (!UNDEF_P(var
.key
)) {
2504 rb_hash_delete_entry(hash
, var
.key
);
2505 return rb_assoc_new(var
.key
, var
.val
);
2513 delete_if_i(VALUE key
, VALUE value
, VALUE hash
)
2515 if (RTEST(rb_yield_values(2, key
, value
))) {
2516 rb_hash_modify(hash
);
2523 hash_enum_size(VALUE hash
, VALUE args
, VALUE eobj
)
2525 return rb_hash_size(hash
);
2530 * hash.delete_if {|key, value| ... } -> self
2531 * hash.delete_if -> new_enumerator
2533 * If a block given, calls the block with each key-value pair;
2534 * deletes each entry for which the block returns a truthy value;
2536 * h = {foo: 0, bar: 1, baz: 2}
2537 * h.delete_if {|key, value| value > 0 } # => {:foo=>0}
2539 * If no block given, returns a new Enumerator:
2540 * h = {foo: 0, bar: 1, baz: 2}
2541 * e = h.delete_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:delete_if>
2542 * e.each { |key, value| value > 0 } # => {:foo=>0}
2546 rb_hash_delete_if(VALUE hash
)
2548 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2549 rb_hash_modify_check(hash
);
2550 if (!RHASH_TABLE_EMPTY_P(hash
)) {
2551 rb_hash_foreach(hash
, delete_if_i
, hash
);
2552 compact_after_delete(hash
);
2559 * hash.reject! {|key, value| ... } -> self or nil
2560 * hash.reject! -> new_enumerator
2562 * Returns +self+, whose remaining entries are those
2563 * for which the block returns +false+ or +nil+:
2564 * h = {foo: 0, bar: 1, baz: 2}
2565 * h.reject! {|key, value| value < 2 } # => {:baz=>2}
2567 * Returns +nil+ if no entries are removed.
2569 * Returns a new Enumerator if no block given:
2570 * h = {foo: 0, bar: 1, baz: 2}
2571 * e = h.reject! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject!>
2572 * e.each {|key, value| key.start_with?('b') } # => {:foo=>0}
2576 rb_hash_reject_bang(VALUE hash
)
2580 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2581 rb_hash_modify(hash
);
2582 n
= RHASH_SIZE(hash
);
2583 if (!n
) return Qnil
;
2584 rb_hash_foreach(hash
, delete_if_i
, hash
);
2585 if (n
== RHASH_SIZE(hash
)) return Qnil
;
2591 * hash.reject {|key, value| ... } -> new_hash
2592 * hash.reject -> new_enumerator
2594 * Returns a new +Hash+ object whose entries are all those
2595 * from +self+ for which the block returns +false+ or +nil+:
2596 * h = {foo: 0, bar: 1, baz: 2}
2597 * h1 = h.reject {|key, value| key.start_with?('b') }
2600 * Returns a new Enumerator if no block given:
2601 * h = {foo: 0, bar: 1, baz: 2}
2602 * e = h.reject # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:reject>
2603 * h1 = e.each {|key, value| key.start_with?('b') }
2608 rb_hash_reject(VALUE hash
)
2612 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2613 result
= hash_dup_with_compare_by_id(hash
);
2614 if (!RHASH_EMPTY_P(hash
)) {
2615 rb_hash_foreach(result
, delete_if_i
, result
);
2616 compact_after_delete(result
);
2623 * hash.slice(*keys) -> new_hash
2625 * Returns a new +Hash+ object containing the entries for the given +keys+:
2626 * h = {foo: 0, bar: 1, baz: 2}
2627 * h.slice(:baz, :foo) # => {:baz=>2, :foo=>0}
2629 * Any given +keys+ that are not found are ignored.
2633 rb_hash_slice(int argc
, VALUE
*argv
, VALUE hash
)
2636 VALUE key
, value
, result
;
2638 if (argc
== 0 || RHASH_EMPTY_P(hash
)) {
2639 return copy_compare_by_id(rb_hash_new(), hash
);
2641 result
= copy_compare_by_id(rb_hash_new_with_size(argc
), hash
);
2643 for (i
= 0; i
< argc
; i
++) {
2645 value
= rb_hash_lookup2(hash
, key
, Qundef
);
2646 if (!UNDEF_P(value
))
2647 rb_hash_aset(result
, key
, value
);
2655 * hsh.except(*keys) -> a_hash
2657 * Returns a new +Hash+ excluding entries for the given +keys+:
2658 * h = { a: 100, b: 200, c: 300 }
2659 * h.except(:a) #=> {:b=>200, :c=>300}
2661 * Any given +keys+ that are not found are ignored.
2665 rb_hash_except(int argc
, VALUE
*argv
, VALUE hash
)
2670 result
= hash_dup_with_compare_by_id(hash
);
2672 for (i
= 0; i
< argc
; i
++) {
2674 rb_hash_delete(result
, key
);
2676 compact_after_delete(result
);
2683 * hash.values_at(*keys) -> new_array
2685 * Returns a new Array containing values for the given +keys+:
2686 * h = {foo: 0, bar: 1, baz: 2}
2687 * h.values_at(:baz, :foo) # => [2, 0]
2689 * The {default values}[rdoc-ref:Hash@Default+Values] are returned
2690 * for any keys that are not found:
2691 * h.values_at(:hello, :foo) # => [nil, 0]
2695 rb_hash_values_at(int argc
, VALUE
*argv
, VALUE hash
)
2697 VALUE result
= rb_ary_new2(argc
);
2700 for (i
=0; i
<argc
; i
++) {
2701 rb_ary_push(result
, rb_hash_aref(hash
, argv
[i
]));
2708 * hash.fetch_values(*keys) -> new_array
2709 * hash.fetch_values(*keys) {|key| ... } -> new_array
2711 * Returns a new Array containing the values associated with the given keys *keys:
2712 * h = {foo: 0, bar: 1, baz: 2}
2713 * h.fetch_values(:baz, :foo) # => [2, 0]
2715 * Returns a new empty Array if no arguments given.
2717 * When a block is given, calls the block with each missing key,
2718 * treating the block's return value as the value for that key:
2719 * h = {foo: 0, bar: 1, baz: 2}
2720 * values = h.fetch_values(:bar, :foo, :bad, :bam) {|key| key.to_s}
2721 * values # => [1, 0, "bad", "bam"]
2723 * When no block is given, raises an exception if any given key is not found.
2727 rb_hash_fetch_values(int argc
, VALUE
*argv
, VALUE hash
)
2729 VALUE result
= rb_ary_new2(argc
);
2732 for (i
=0; i
<argc
; i
++) {
2733 rb_ary_push(result
, rb_hash_fetch(hash
, argv
[i
]));
2739 keep_if_i(VALUE key
, VALUE value
, VALUE hash
)
2741 if (!RTEST(rb_yield_values(2, key
, value
))) {
2742 rb_hash_modify(hash
);
2750 * hash.select {|key, value| ... } -> new_hash
2751 * hash.select -> new_enumerator
2753 * Returns a new +Hash+ object whose entries are those for which the block returns a truthy value:
2754 * h = {foo: 0, bar: 1, baz: 2}
2755 * h.select {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2757 * Returns a new Enumerator if no block given:
2758 * h = {foo: 0, bar: 1, baz: 2}
2759 * e = h.select # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select>
2760 * e.each {|key, value| value < 2 } # => {:foo=>0, :bar=>1}
2764 rb_hash_select(VALUE hash
)
2768 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2769 result
= hash_dup_with_compare_by_id(hash
);
2770 if (!RHASH_EMPTY_P(hash
)) {
2771 rb_hash_foreach(result
, keep_if_i
, result
);
2772 compact_after_delete(result
);
2779 * hash.select! {|key, value| ... } -> self or nil
2780 * hash.select! -> new_enumerator
2782 * Returns +self+, whose entries are those for which the block returns a truthy value:
2783 * h = {foo: 0, bar: 1, baz: 2}
2784 * h.select! {|key, value| value < 2 } => {:foo=>0, :bar=>1}
2786 * Returns +nil+ if no entries were removed.
2788 * Returns a new Enumerator if no block given:
2789 * h = {foo: 0, bar: 1, baz: 2}
2790 * e = h.select! # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:select!>
2791 * e.each { |key, value| value < 2 } # => {:foo=>0, :bar=>1}
2795 rb_hash_select_bang(VALUE hash
)
2799 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2800 rb_hash_modify_check(hash
);
2801 n
= RHASH_SIZE(hash
);
2802 if (!n
) return Qnil
;
2803 rb_hash_foreach(hash
, keep_if_i
, hash
);
2804 if (n
== RHASH_SIZE(hash
)) return Qnil
;
2810 * hash.keep_if {|key, value| ... } -> self
2811 * hash.keep_if -> new_enumerator
2813 * Calls the block for each key-value pair;
2814 * retains the entry if the block returns a truthy value;
2815 * otherwise deletes the entry; returns +self+.
2816 * h = {foo: 0, bar: 1, baz: 2}
2817 * h.keep_if { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2819 * Returns a new Enumerator if no block given:
2820 * h = {foo: 0, bar: 1, baz: 2}
2821 * e = h.keep_if # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:keep_if>
2822 * e.each { |key, value| key.start_with?('b') } # => {:bar=>1, :baz=>2}
2826 rb_hash_keep_if(VALUE hash
)
2828 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
2829 rb_hash_modify_check(hash
);
2830 if (!RHASH_TABLE_EMPTY_P(hash
)) {
2831 rb_hash_foreach(hash
, keep_if_i
, hash
);
2837 clear_i(VALUE key
, VALUE value
, VALUE dummy
)
2844 * hash.clear -> self
2846 * Removes all hash entries; returns +self+.
2850 rb_hash_clear(VALUE hash
)
2852 rb_hash_modify_check(hash
);
2854 if (hash_iterating_p(hash
)) {
2855 rb_hash_foreach(hash
, clear_i
, 0);
2857 else if (RHASH_AR_TABLE_P(hash
)) {
2861 st_clear(RHASH_ST_TABLE(hash
));
2862 compact_after_delete(hash
);
2869 hash_aset(st_data_t
*key
, st_data_t
*val
, struct update_arg
*arg
, int existing
)
2876 rb_hash_key_str(VALUE key
)
2878 if (!RB_FL_ANY_RAW(key
, FL_EXIVAR
) && RBASIC_CLASS(key
) == rb_cString
) {
2879 return rb_fstring(key
);
2882 return rb_str_new_frozen(key
);
2887 hash_aset_str(st_data_t
*key
, st_data_t
*val
, struct update_arg
*arg
, int existing
)
2889 if (!existing
&& !RB_OBJ_FROZEN(*key
)) {
2890 *key
= rb_hash_key_str(*key
);
2892 return hash_aset(key
, val
, arg
, existing
);
2895 NOINSERT_UPDATE_CALLBACK(hash_aset
)
2896 NOINSERT_UPDATE_CALLBACK(hash_aset_str
)
2900 * hash[key] = value -> value
2901 * hash.store(key, value)
2903 * Associates the given +value+ with the given +key+; returns +value+.
2905 * If the given +key+ exists, replaces its value with the given +value+;
2906 * the ordering is not affected
2907 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2908 * h = {foo: 0, bar: 1}
2909 * h[:foo] = 2 # => 2
2910 * h.store(:bar, 3) # => 3
2911 * h # => {:foo=>2, :bar=>3}
2913 * If +key+ does not exist, adds the +key+ and +value+;
2914 * the new entry is last in the order
2915 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
2916 * h = {foo: 0, bar: 1}
2917 * h[:baz] = 2 # => 2
2918 * h.store(:bat, 3) # => 3
2919 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
2923 rb_hash_aset(VALUE hash
, VALUE key
, VALUE val
)
2925 bool iter_p
= hash_iterating_p(hash
);
2927 rb_hash_modify(hash
);
2929 if (!RHASH_STRING_KEY_P(hash
, key
)) {
2930 RHASH_UPDATE_ITER(hash
, iter_p
, key
, hash_aset
, val
);
2933 RHASH_UPDATE_ITER(hash
, iter_p
, key
, hash_aset_str
, val
);
2940 * hash.replace(other_hash) -> self
2942 * Replaces the entire contents of +self+ with the contents of +other_hash+;
2944 * h = {foo: 0, bar: 1, baz: 2}
2945 * h.replace({bat: 3, bam: 4}) # => {:bat=>3, :bam=>4}
2949 rb_hash_replace(VALUE hash
, VALUE hash2
)
2951 rb_hash_modify_check(hash
);
2952 if (hash
== hash2
) return hash
;
2953 if (hash_iterating_p(hash
)) {
2954 rb_raise(rb_eRuntimeError
, "can't replace hash during iteration");
2956 hash2
= to_hash(hash2
);
2958 COPY_DEFAULT(hash
, hash2
);
2960 if (RHASH_AR_TABLE_P(hash
)) {
2961 hash_ar_free_and_clear_table(hash
);
2964 hash_st_free_and_clear_table(hash
);
2967 hash_copy(hash
, hash2
);
2974 * hash.length -> integer
2975 * hash.size -> integer
2977 * Returns the count of entries in +self+:
2979 * {foo: 0, bar: 1, baz: 2}.length # => 3
2984 rb_hash_size(VALUE hash
)
2986 return INT2FIX(RHASH_SIZE(hash
));
2990 rb_hash_size_num(VALUE hash
)
2992 return (long)RHASH_SIZE(hash
);
2997 * hash.empty? -> true or false
2999 * Returns +true+ if there are no hash entries, +false+ otherwise:
3000 * {}.empty? # => true
3001 * {foo: 0, bar: 1, baz: 2}.empty? # => false
3005 rb_hash_empty_p(VALUE hash
)
3007 return RBOOL(RHASH_EMPTY_P(hash
));
3011 each_value_i(VALUE key
, VALUE value
, VALUE _
)
3019 * hash.each_value {|value| ... } -> self
3020 * hash.each_value -> new_enumerator
3022 * Calls the given block with each value; returns +self+:
3023 * h = {foo: 0, bar: 1, baz: 2}
3024 * h.each_value {|value| puts value } # => {:foo=>0, :bar=>1, :baz=>2}
3030 * Returns a new Enumerator if no block given:
3031 * h = {foo: 0, bar: 1, baz: 2}
3032 * e = h.each_value # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_value>
3033 * h1 = e.each {|value| puts value }
3034 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3042 rb_hash_each_value(VALUE hash
)
3044 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3045 rb_hash_foreach(hash
, each_value_i
, 0);
3050 each_key_i(VALUE key
, VALUE value
, VALUE _
)
3058 * hash.each_key {|key| ... } -> self
3059 * hash.each_key -> new_enumerator
3061 * Calls the given block with each key; returns +self+:
3062 * h = {foo: 0, bar: 1, baz: 2}
3063 * h.each_key {|key| puts key } # => {:foo=>0, :bar=>1, :baz=>2}
3069 * Returns a new Enumerator if no block given:
3070 * h = {foo: 0, bar: 1, baz: 2}
3071 * e = h.each_key # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_key>
3072 * h1 = e.each {|key| puts key }
3073 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3080 rb_hash_each_key(VALUE hash
)
3082 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3083 rb_hash_foreach(hash
, each_key_i
, 0);
3088 each_pair_i(VALUE key
, VALUE value
, VALUE _
)
3090 rb_yield(rb_assoc_new(key
, value
));
3095 each_pair_i_fast(VALUE key
, VALUE value
, VALUE _
)
3100 rb_yield_values2(2, argv
);
3106 * hash.each {|key, value| ... } -> self
3107 * hash.each_pair {|key, value| ... } -> self
3108 * hash.each -> new_enumerator
3109 * hash.each_pair -> new_enumerator
3111 * Calls the given block with each key-value pair; returns +self+:
3112 * h = {foo: 0, bar: 1, baz: 2}
3113 * h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}
3119 * Returns a new Enumerator if no block given:
3120 * h = {foo: 0, bar: 1, baz: 2}
3121 * e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
3122 * h1 = e.each {|key, value| puts "#{key}: #{value}"}
3123 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3131 rb_hash_each_pair(VALUE hash
)
3133 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3134 if (rb_block_pair_yield_optimizable())
3135 rb_hash_foreach(hash
, each_pair_i_fast
, 0);
3137 rb_hash_foreach(hash
, each_pair_i
, 0);
3141 struct transform_keys_args
{
3148 transform_keys_hash_i(VALUE key
, VALUE value
, VALUE transarg
)
3150 struct transform_keys_args
*p
= (void *)transarg
;
3151 VALUE trans
= p
->trans
, result
= p
->result
;
3152 VALUE new_key
= rb_hash_lookup2(trans
, key
, Qundef
);
3153 if (UNDEF_P(new_key
)) {
3155 new_key
= rb_yield(key
);
3159 rb_hash_aset(result
, new_key
, value
);
3164 transform_keys_i(VALUE key
, VALUE value
, VALUE result
)
3166 VALUE new_key
= rb_yield(key
);
3167 rb_hash_aset(result
, new_key
, value
);
3173 * hash.transform_keys {|key| ... } -> new_hash
3174 * hash.transform_keys(hash2) -> new_hash
3175 * hash.transform_keys(hash2) {|other_key| ...} -> new_hash
3176 * hash.transform_keys -> new_enumerator
3178 * Returns a new +Hash+ object; each entry has:
3179 * * A key provided by the block.
3180 * * The value from +self+.
3182 * An optional hash argument can be provided to map keys to new keys.
3183 * Any key not given will be mapped using the provided block,
3184 * or remain the same if no block is given.
3187 * h = {foo: 0, bar: 1, baz: 2}
3188 * h1 = h.transform_keys {|key| key.to_s }
3189 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3191 * h.transform_keys(foo: :bar, bar: :foo)
3192 * #=> {bar: 0, foo: 1, baz: 2}
3194 * h.transform_keys(foo: :hello, &:to_s)
3195 * #=> {:hello=>0, "bar"=>1, "baz"=>2}
3197 * Overwrites values for duplicate keys:
3198 * h = {foo: 0, bar: 1, baz: 2}
3199 * h1 = h.transform_keys {|key| :bat }
3202 * Returns a new Enumerator if no block given:
3203 * h = {foo: 0, bar: 1, baz: 2}
3204 * e = h.transform_keys # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_keys>
3205 * h1 = e.each { |key| key.to_s }
3206 * h1 # => {"foo"=>0, "bar"=>1, "baz"=>2}
3209 rb_hash_transform_keys(int argc
, VALUE
*argv
, VALUE hash
)
3212 struct transform_keys_args transarg
= {0};
3214 argc
= rb_check_arity(argc
, 0, 1);
3216 transarg
.trans
= to_hash(argv
[0]);
3217 transarg
.block_given
= rb_block_given_p();
3220 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3222 result
= rb_hash_new();
3223 if (!RHASH_EMPTY_P(hash
)) {
3224 if (transarg
.trans
) {
3225 transarg
.result
= result
;
3226 rb_hash_foreach(hash
, transform_keys_hash_i
, (VALUE
)&transarg
);
3229 rb_hash_foreach(hash
, transform_keys_i
, result
);
3236 static int flatten_i(VALUE key
, VALUE val
, VALUE ary
);
3240 * hash.transform_keys! {|key| ... } -> self
3241 * hash.transform_keys!(hash2) -> self
3242 * hash.transform_keys!(hash2) {|other_key| ...} -> self
3243 * hash.transform_keys! -> new_enumerator
3245 * Same as Hash#transform_keys but modifies the receiver in place
3246 * instead of returning a new hash.
3249 rb_hash_transform_keys_bang(int argc
, VALUE
*argv
, VALUE hash
)
3252 int block_given
= 0;
3254 argc
= rb_check_arity(argc
, 0, 1);
3256 trans
= to_hash(argv
[0]);
3257 block_given
= rb_block_given_p();
3260 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3262 rb_hash_modify_check(hash
);
3263 if (!RHASH_TABLE_EMPTY_P(hash
)) {
3265 VALUE new_keys
= hash_alloc(0);
3266 VALUE pairs
= rb_ary_hidden_new(RHASH_SIZE(hash
) * 2);
3267 rb_hash_foreach(hash
, flatten_i
, pairs
);
3268 for (i
= 0; i
< RARRAY_LEN(pairs
); i
+= 2) {
3269 VALUE key
= RARRAY_AREF(pairs
, i
), new_key
, val
;
3272 new_key
= rb_yield(key
);
3274 else if (!UNDEF_P(new_key
= rb_hash_lookup2(trans
, key
, Qundef
))) {
3275 /* use the transformed key */
3277 else if (block_given
) {
3278 new_key
= rb_yield(key
);
3283 val
= RARRAY_AREF(pairs
, i
+1);
3284 if (!hash_stlike_lookup(new_keys
, key
, NULL
)) {
3285 rb_hash_stlike_delete(hash
, &key
, NULL
);
3287 rb_hash_aset(hash
, new_key
, val
);
3288 rb_hash_aset(new_keys
, new_key
, Qnil
);
3290 rb_ary_clear(pairs
);
3291 rb_hash_clear(new_keys
);
3293 compact_after_delete(hash
);
3298 transform_values_foreach_func(st_data_t key
, st_data_t value
, st_data_t argp
, int error
)
3304 transform_values_foreach_replace(st_data_t
*key
, st_data_t
*value
, st_data_t argp
, int existing
)
3306 VALUE new_value
= rb_yield((VALUE
)*value
);
3307 VALUE hash
= (VALUE
)argp
;
3308 rb_hash_modify(hash
);
3309 RB_OBJ_WRITE(hash
, value
, new_value
);
3315 * hash.transform_values {|value| ... } -> new_hash
3316 * hash.transform_values -> new_enumerator
3318 * Returns a new +Hash+ object; each entry has:
3319 * * A key from +self+.
3320 * * A value provided by the block.
3323 * h = {foo: 0, bar: 1, baz: 2}
3324 * h1 = h.transform_values {|value| value * 100}
3325 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3327 * Returns a new Enumerator if no block given:
3328 * h = {foo: 0, bar: 1, baz: 2}
3329 * e = h.transform_values # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:transform_values>
3330 * h1 = e.each { |value| value * 100}
3331 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3334 rb_hash_transform_values(VALUE hash
)
3338 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3339 result
= hash_dup_with_compare_by_id(hash
);
3340 SET_DEFAULT(result
, Qnil
);
3342 if (!RHASH_EMPTY_P(hash
)) {
3343 rb_hash_stlike_foreach_with_replace(result
, transform_values_foreach_func
, transform_values_foreach_replace
, result
);
3344 compact_after_delete(result
);
3352 * hash.transform_values! {|value| ... } -> self
3353 * hash.transform_values! -> new_enumerator
3355 * Returns +self+, whose keys are unchanged, and whose values are determined by the given block.
3356 * h = {foo: 0, bar: 1, baz: 2}
3357 * h.transform_values! {|value| value * 100} # => {:foo=>0, :bar=>100, :baz=>200}
3359 * Returns a new Enumerator if no block given:
3360 * h = {foo: 0, bar: 1, baz: 2}
3361 * e = h.transform_values! # => #<Enumerator: {:foo=>0, :bar=>100, :baz=>200}:transform_values!>
3362 * h1 = e.each {|value| value * 100}
3363 * h1 # => {:foo=>0, :bar=>100, :baz=>200}
3366 rb_hash_transform_values_bang(VALUE hash
)
3368 RETURN_SIZED_ENUMERATOR(hash
, 0, 0, hash_enum_size
);
3369 rb_hash_modify_check(hash
);
3371 if (!RHASH_TABLE_EMPTY_P(hash
)) {
3372 rb_hash_stlike_foreach_with_replace(hash
, transform_values_foreach_func
, transform_values_foreach_replace
, hash
);
3379 to_a_i(VALUE key
, VALUE value
, VALUE ary
)
3381 rb_ary_push(ary
, rb_assoc_new(key
, value
));
3387 * hash.to_a -> new_array
3389 * Returns a new Array of 2-element Array objects;
3390 * each nested Array contains a key-value pair from +self+:
3391 * h = {foo: 0, bar: 1, baz: 2}
3392 * h.to_a # => [[:foo, 0], [:bar, 1], [:baz, 2]]
3396 rb_hash_to_a(VALUE hash
)
3400 ary
= rb_ary_new_capa(RHASH_SIZE(hash
));
3401 rb_hash_foreach(hash
, to_a_i
, ary
);
3407 inspect_i(VALUE key
, VALUE value
, VALUE str
)
3411 str2
= rb_inspect(key
);
3412 if (RSTRING_LEN(str
) > 1) {
3413 rb_str_buf_cat_ascii(str
, ", ");
3416 rb_enc_copy(str
, str2
);
3418 rb_str_buf_append(str
, str2
);
3419 rb_str_buf_cat_ascii(str
, "=>");
3420 str2
= rb_inspect(value
);
3421 rb_str_buf_append(str
, str2
);
3427 inspect_hash(VALUE hash
, VALUE dummy
, int recur
)
3431 if (recur
) return rb_usascii_str_new2("{...}");
3432 str
= rb_str_buf_new2("{");
3433 rb_hash_foreach(hash
, inspect_i
, str
);
3434 rb_str_buf_cat2(str
, "}");
3441 * hash.inspect -> new_string
3443 * Returns a new String containing the hash entries:
3445 * h = {foo: 0, bar: 1, baz: 2}
3446 * h.inspect # => "{:foo=>0, :bar=>1, :baz=>2}"
3451 rb_hash_inspect(VALUE hash
)
3453 if (RHASH_EMPTY_P(hash
))
3454 return rb_usascii_str_new2("{}");
3455 return rb_exec_recursive(inspect_hash
, hash
, 0);
3460 * hash.to_hash -> self
3465 rb_hash_to_hash(VALUE hash
)
3471 rb_hash_set_pair(VALUE hash
, VALUE arg
)
3475 pair
= rb_check_array_type(arg
);
3477 rb_raise(rb_eTypeError
, "wrong element type %s (expected array)",
3478 rb_builtin_class_name(arg
));
3480 if (RARRAY_LEN(pair
) != 2) {
3481 rb_raise(rb_eArgError
, "element has wrong array length (expected 2, was %ld)",
3484 rb_hash_aset(hash
, RARRAY_AREF(pair
, 0), RARRAY_AREF(pair
, 1));
3489 to_h_i(VALUE key
, VALUE value
, VALUE hash
)
3491 rb_hash_set_pair(hash
, rb_yield_values(2, key
, value
));
3496 rb_hash_to_h_block(VALUE hash
)
3498 VALUE h
= rb_hash_new_with_size(RHASH_SIZE(hash
));
3499 rb_hash_foreach(hash
, to_h_i
, h
);
3505 * hash.to_h -> self or new_hash
3506 * hash.to_h {|key, value| ... } -> new_hash
3508 * For an instance of +Hash+, returns +self+.
3510 * For a subclass of +Hash+, returns a new +Hash+
3511 * containing the content of +self+.
3513 * When a block is given, returns a new +Hash+ object
3514 * whose content is based on the block;
3515 * the block should return a 2-element Array object
3516 * specifying the key-value pair to be included in the returned Array:
3517 * h = {foo: 0, bar: 1, baz: 2}
3518 * h1 = h.to_h {|key, value| [value, key] }
3519 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3523 rb_hash_to_h(VALUE hash
)
3525 if (rb_block_given_p()) {
3526 return rb_hash_to_h_block(hash
);
3528 if (rb_obj_class(hash
) != rb_cHash
) {
3529 const VALUE flags
= RBASIC(hash
)->flags
;
3530 hash
= hash_dup(hash
, rb_cHash
, flags
& RHASH_PROC_DEFAULT
);
3536 keys_i(VALUE key
, VALUE value
, VALUE ary
)
3538 rb_ary_push(ary
, key
);
3544 * hash.keys -> new_array
3546 * Returns a new Array containing all keys in +self+:
3547 * h = {foo: 0, bar: 1, baz: 2}
3548 * h.keys # => [:foo, :bar, :baz]
3552 rb_hash_keys(VALUE hash
)
3554 st_index_t size
= RHASH_SIZE(hash
);
3555 VALUE keys
= rb_ary_new_capa(size
);
3557 if (size
== 0) return keys
;
3559 if (ST_DATA_COMPATIBLE_P(VALUE
)) {
3560 RARRAY_PTR_USE(keys
, ptr
, {
3561 if (RHASH_AR_TABLE_P(hash
)) {
3562 size
= ar_keys(hash
, ptr
, size
);
3565 st_table
*table
= RHASH_ST_TABLE(hash
);
3566 size
= st_keys(table
, ptr
, size
);
3569 rb_gc_writebarrier_remember(keys
);
3570 rb_ary_set_len(keys
, size
);
3573 rb_hash_foreach(hash
, keys_i
, keys
);
3580 values_i(VALUE key
, VALUE value
, VALUE ary
)
3582 rb_ary_push(ary
, value
);
3588 * hash.values -> new_array
3590 * Returns a new Array containing all values in +self+:
3591 * h = {foo: 0, bar: 1, baz: 2}
3592 * h.values # => [0, 1, 2]
3596 rb_hash_values(VALUE hash
)
3599 st_index_t size
= RHASH_SIZE(hash
);
3601 values
= rb_ary_new_capa(size
);
3602 if (size
== 0) return values
;
3604 if (ST_DATA_COMPATIBLE_P(VALUE
)) {
3605 if (RHASH_AR_TABLE_P(hash
)) {
3606 rb_gc_writebarrier_remember(values
);
3607 RARRAY_PTR_USE(values
, ptr
, {
3608 size
= ar_values(hash
, ptr
, size
);
3611 else if (RHASH_ST_TABLE_P(hash
)) {
3612 st_table
*table
= RHASH_ST_TABLE(hash
);
3613 rb_gc_writebarrier_remember(values
);
3614 RARRAY_PTR_USE(values
, ptr
, {
3615 size
= st_values(table
, ptr
, size
);
3618 rb_ary_set_len(values
, size
);
3622 rb_hash_foreach(hash
, values_i
, values
);
3630 * hash.include?(key) -> true or false
3631 * hash.has_key?(key) -> true or false
3632 * hash.key?(key) -> true or false
3633 * hash.member?(key) -> true or false
3635 * Returns +true+ if +key+ is a key in +self+, otherwise +false+.
3639 rb_hash_has_key(VALUE hash
, VALUE key
)
3641 return RBOOL(hash_stlike_lookup(hash
, key
, NULL
));
3645 rb_hash_search_value(VALUE key
, VALUE value
, VALUE arg
)
3647 VALUE
*data
= (VALUE
*)arg
;
3649 if (rb_equal(value
, data
[1])) {
3658 * hash.has_value?(value) -> true or false
3659 * hash.value?(value) -> true or false
3661 * Returns +true+ if +value+ is a value in +self+, otherwise +false+.
3665 rb_hash_has_value(VALUE hash
, VALUE val
)
3671 rb_hash_foreach(hash
, rb_hash_search_value
, (VALUE
)data
);
3682 eql_i(VALUE key
, VALUE val1
, VALUE arg
)
3684 struct equal_data
*data
= (struct equal_data
*)arg
;
3687 if (!hash_stlike_lookup(data
->hash
, key
, &val2
)) {
3688 data
->result
= Qfalse
;
3692 if (!(data
->eql
? rb_eql(val1
, (VALUE
)val2
) : (int)rb_equal(val1
, (VALUE
)val2
))) {
3693 data
->result
= Qfalse
;
3701 recursive_eql(VALUE hash
, VALUE dt
, int recur
)
3703 struct equal_data
*data
;
3705 if (recur
) return Qtrue
; /* Subtle! */
3706 data
= (struct equal_data
*)dt
;
3707 data
->result
= Qtrue
;
3708 rb_hash_foreach(hash
, eql_i
, dt
);
3710 return data
->result
;
3714 hash_equal(VALUE hash1
, VALUE hash2
, int eql
)
3716 struct equal_data data
;
3718 if (hash1
== hash2
) return Qtrue
;
3719 if (!RB_TYPE_P(hash2
, T_HASH
)) {
3720 if (!rb_respond_to(hash2
, idTo_hash
)) {
3724 if (rb_eql(hash2
, hash1
)) {
3732 return rb_equal(hash2
, hash1
);
3735 if (RHASH_SIZE(hash1
) != RHASH_SIZE(hash2
))
3737 if (!RHASH_TABLE_EMPTY_P(hash1
) && !RHASH_TABLE_EMPTY_P(hash2
)) {
3738 if (RHASH_TYPE(hash1
) != RHASH_TYPE(hash2
)) {
3744 return rb_exec_recursive_paired(recursive_eql
, hash1
, hash2
, (VALUE
)&data
);
3749 if (!(rb_equal(RHASH_IFNONE(hash1
), RHASH_IFNONE(hash2
)) &&
3750 FL_TEST(hash1
, RHASH_PROC_DEFAULT
) == FL_TEST(hash2
, RHASH_PROC_DEFAULT
)))
3758 * hash == object -> true or false
3760 * Returns +true+ if all of the following are true:
3761 * * +object+ is a +Hash+ object.
3762 * * +hash+ and +object+ have the same keys (regardless of order).
3763 * * For each key +key+, <tt>hash[key] == object[key]</tt>.
3765 * Otherwise, returns +false+.
3768 * h1 = {foo: 0, bar: 1, baz: 2}
3769 * h2 = {foo: 0, bar: 1, baz: 2}
3770 * h1 == h2 # => true
3771 * h3 = {baz: 2, bar: 1, foo: 0}
3772 * h1 == h3 # => true
3776 rb_hash_equal(VALUE hash1
, VALUE hash2
)
3778 return hash_equal(hash1
, hash2
, FALSE
);
3783 * hash.eql?(object) -> true or false
3785 * Returns +true+ if all of the following are true:
3786 * * +object+ is a +Hash+ object.
3787 * * +hash+ and +object+ have the same keys (regardless of order).
3788 * * For each key +key+, <tt>h[key].eql?(object[key])</tt>.
3790 * Otherwise, returns +false+.
3792 * h1 = {foo: 0, bar: 1, baz: 2}
3793 * h2 = {foo: 0, bar: 1, baz: 2}
3794 * h1.eql? h2 # => true
3795 * h3 = {baz: 2, bar: 1, foo: 0}
3796 * h1.eql? h3 # => true
3800 rb_hash_eql(VALUE hash1
, VALUE hash2
)
3802 return hash_equal(hash1
, hash2
, TRUE
);
3806 hash_i(VALUE key
, VALUE val
, VALUE arg
)
3808 st_index_t
*hval
= (st_index_t
*)arg
;
3809 st_index_t hdata
[2];
3811 hdata
[0] = rb_hash(key
);
3812 hdata
[1] = rb_hash(val
);
3813 *hval
^= st_hash(hdata
, sizeof(hdata
), 0);
3819 * hash.hash -> an_integer
3821 * Returns the Integer hash-code for the hash.
3823 * Two +Hash+ objects have the same hash-code if their content is the same
3824 * (regardless of order):
3825 * h1 = {foo: 0, bar: 1, baz: 2}
3826 * h2 = {baz: 2, bar: 1, foo: 0}
3827 * h2.hash == h1.hash # => true
3828 * h2.eql? h1 # => true
3832 rb_hash_hash(VALUE hash
)
3834 st_index_t size
= RHASH_SIZE(hash
);
3835 st_index_t hval
= rb_hash_start(size
);
3836 hval
= rb_hash_uint(hval
, (st_index_t
)rb_hash_hash
);
3838 rb_hash_foreach(hash
, hash_i
, (VALUE
)&hval
);
3840 hval
= rb_hash_end(hval
);
3841 return ST2FIX(hval
);
3845 rb_hash_invert_i(VALUE key
, VALUE value
, VALUE hash
)
3847 rb_hash_aset(hash
, value
, key
);
3853 * hash.invert -> new_hash
3855 * Returns a new +Hash+ object with the each key-value pair inverted:
3856 * h = {foo: 0, bar: 1, baz: 2}
3858 * h1 # => {0=>:foo, 1=>:bar, 2=>:baz}
3860 * Overwrites any repeated new keys:
3861 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
3862 * h = {foo: 0, bar: 0, baz: 0}
3863 * h.invert # => {0=>:baz}
3867 rb_hash_invert(VALUE hash
)
3869 VALUE h
= rb_hash_new_with_size(RHASH_SIZE(hash
));
3871 rb_hash_foreach(hash
, rb_hash_invert_i
, h
);
3876 rb_hash_update_i(VALUE key
, VALUE value
, VALUE hash
)
3878 rb_hash_aset(hash
, key
, value
);
3883 rb_hash_update_block_callback(st_data_t
*key
, st_data_t
*value
, struct update_arg
*arg
, int existing
)
3885 st_data_t newvalue
= arg
->arg
;
3888 newvalue
= (st_data_t
)rb_yield_values(3, (VALUE
)*key
, (VALUE
)*value
, (VALUE
)newvalue
);
3890 else if (RHASH_STRING_KEY_P(arg
->hash
, *key
) && !RB_OBJ_FROZEN(*key
)) {
3891 *key
= rb_hash_key_str(*key
);
3897 NOINSERT_UPDATE_CALLBACK(rb_hash_update_block_callback
)
3900 rb_hash_update_block_i(VALUE key
, VALUE value
, VALUE hash
)
3902 RHASH_UPDATE(hash
, key
, rb_hash_update_block_callback
, value
);
3908 * hash.merge! -> self
3909 * hash.merge!(*other_hashes) -> self
3910 * hash.merge!(*other_hashes) { |key, old_value, new_value| ... } -> self
3912 * Merges each of +other_hashes+ into +self+; returns +self+.
3914 * Each argument in +other_hashes+ must be a +Hash+.
3916 * With arguments and no block:
3917 * * Returns +self+, after the given hashes are merged into it.
3918 * * The given hashes are merged left to right.
3919 * * Each new entry is added at the end.
3920 * * Each duplicate-key entry's value overwrites the previous value.
3923 * h = {foo: 0, bar: 1, baz: 2}
3924 * h1 = {bat: 3, bar: 4}
3925 * h2 = {bam: 5, bat:6}
3926 * h.merge!(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
3928 * With arguments and a block:
3929 * * Returns +self+, after the given hashes are merged.
3930 * * The given hashes are merged left to right.
3931 * * Each new-key entry is added at the end.
3932 * * For each duplicate key:
3933 * * Calls the block with the key and the old and new values.
3934 * * The block's return value becomes the new value for the entry.
3937 * h = {foo: 0, bar: 1, baz: 2}
3938 * h1 = {bat: 3, bar: 4}
3939 * h2 = {bam: 5, bat:6}
3940 * h3 = h.merge!(h1, h2) { |key, old_value, new_value| old_value + new_value }
3941 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
3943 * With no arguments:
3944 * * Returns +self+, unmodified.
3945 * * The block, if given, is ignored.
3948 * h = {foo: 0, bar: 1, baz: 2}
3949 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
3950 * h1 = h.merge! { |key, old_value, new_value| raise 'Cannot happen' }
3951 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
3955 rb_hash_update(int argc
, VALUE
*argv
, VALUE self
)
3958 bool block_given
= rb_block_given_p();
3960 rb_hash_modify(self
);
3961 for (i
= 0; i
< argc
; i
++){
3962 VALUE hash
= to_hash(argv
[i
]);
3964 rb_hash_foreach(hash
, rb_hash_update_block_i
, self
);
3967 rb_hash_foreach(hash
, rb_hash_update_i
, self
);
3973 struct update_func_arg
{
3976 rb_hash_update_func
*func
;
3980 rb_hash_update_func_callback(st_data_t
*key
, st_data_t
*value
, struct update_arg
*arg
, int existing
)
3982 struct update_func_arg
*uf_arg
= (struct update_func_arg
*)arg
->arg
;
3983 VALUE newvalue
= uf_arg
->value
;
3986 newvalue
= (*uf_arg
->func
)((VALUE
)*key
, (VALUE
)*value
, newvalue
);
3992 NOINSERT_UPDATE_CALLBACK(rb_hash_update_func_callback
)
3995 rb_hash_update_func_i(VALUE key
, VALUE value
, VALUE arg0
)
3997 struct update_func_arg
*arg
= (struct update_func_arg
*)arg0
;
3998 VALUE hash
= arg
->hash
;
4001 RHASH_UPDATE(hash
, key
, rb_hash_update_func_callback
, (VALUE
)arg
);
4006 rb_hash_update_by(VALUE hash1
, VALUE hash2
, rb_hash_update_func
*func
)
4008 rb_hash_modify(hash1
);
4009 hash2
= to_hash(hash2
);
4011 struct update_func_arg arg
;
4014 rb_hash_foreach(hash2
, rb_hash_update_func_i
, (VALUE
)&arg
);
4017 rb_hash_foreach(hash2
, rb_hash_update_i
, hash1
);
4024 * hash.merge -> copy_of_self
4025 * hash.merge(*other_hashes) -> new_hash
4026 * hash.merge(*other_hashes) { |key, old_value, new_value| ... } -> new_hash
4028 * Returns the new +Hash+ formed by merging each of +other_hashes+
4029 * into a copy of +self+.
4031 * Each argument in +other_hashes+ must be a +Hash+.
4035 * With arguments and no block:
4036 * * Returns the new +Hash+ object formed by merging each successive
4037 * +Hash+ in +other_hashes+ into +self+.
4038 * * Each new-key entry is added at the end.
4039 * * Each duplicate-key entry's value overwrites the previous value.
4042 * h = {foo: 0, bar: 1, baz: 2}
4043 * h1 = {bat: 3, bar: 4}
4044 * h2 = {bam: 5, bat:6}
4045 * h.merge(h1, h2) # => {:foo=>0, :bar=>4, :baz=>2, :bat=>6, :bam=>5}
4047 * With arguments and a block:
4048 * * Returns a new +Hash+ object that is the merge of +self+ and each given hash.
4049 * * The given hashes are merged left to right.
4050 * * Each new-key entry is added at the end.
4051 * * For each duplicate key:
4052 * * Calls the block with the key and the old and new values.
4053 * * The block's return value becomes the new value for the entry.
4056 * h = {foo: 0, bar: 1, baz: 2}
4057 * h1 = {bat: 3, bar: 4}
4058 * h2 = {bam: 5, bat:6}
4059 * h3 = h.merge(h1, h2) { |key, old_value, new_value| old_value + new_value }
4060 * h3 # => {:foo=>0, :bar=>5, :baz=>2, :bat=>9, :bam=>5}
4062 * With no arguments:
4063 * * Returns a copy of +self+.
4064 * * The block, if given, is ignored.
4067 * h = {foo: 0, bar: 1, baz: 2}
4068 * h.merge # => {:foo=>0, :bar=>1, :baz=>2}
4069 * h1 = h.merge { |key, old_value, new_value| raise 'Cannot happen' }
4070 * h1 # => {:foo=>0, :bar=>1, :baz=>2}
4074 rb_hash_merge(int argc
, VALUE
*argv
, VALUE self
)
4076 return rb_hash_update(argc
, argv
, copy_compare_by_id(rb_hash_dup(self
), self
));
4080 assoc_cmp(VALUE a
, VALUE b
)
4082 return !RTEST(rb_equal(a
, b
));
4091 assoc_lookup(VALUE arg
)
4093 struct assoc_arg
*p
= (struct assoc_arg
*)arg
;
4095 if (st_lookup(p
->tbl
, p
->key
, &data
)) return (VALUE
)data
;
4100 assoc_i(VALUE key
, VALUE val
, VALUE arg
)
4102 VALUE
*args
= (VALUE
*)arg
;
4104 if (RTEST(rb_equal(args
[0], key
))) {
4105 args
[1] = rb_assoc_new(key
, val
);
4113 * hash.assoc(key) -> new_array or nil
4115 * If the given +key+ is found, returns a 2-element Array containing that key and its value:
4116 * h = {foo: 0, bar: 1, baz: 2}
4117 * h.assoc(:bar) # => [:bar, 1]
4119 * Returns +nil+ if key +key+ is not found.
4123 rb_hash_assoc(VALUE hash
, VALUE key
)
4127 if (RHASH_EMPTY_P(hash
)) return Qnil
;
4129 if (RHASH_ST_TABLE_P(hash
) && !RHASH_IDENTHASH_P(hash
)) {
4130 VALUE value
= Qundef
;
4131 st_table assoctable
= *RHASH_ST_TABLE(hash
);
4132 assoctable
.type
= &(struct st_hash_type
){
4133 .compare
= assoc_cmp
,
4134 .hash
= assoctable
.type
->hash
,
4136 VALUE arg
= (VALUE
)&(struct assoc_arg
){
4138 .key
= (st_data_t
)key
,
4141 if (RB_OBJ_FROZEN(hash
)) {
4142 value
= assoc_lookup(arg
);
4145 hash_iter_lev_inc(hash
);
4146 value
= rb_ensure(assoc_lookup
, arg
, hash_foreach_ensure
, hash
);
4149 if (!UNDEF_P(value
)) return rb_assoc_new(key
, value
);
4154 rb_hash_foreach(hash
, assoc_i
, (VALUE
)args
);
4159 rassoc_i(VALUE key
, VALUE val
, VALUE arg
)
4161 VALUE
*args
= (VALUE
*)arg
;
4163 if (RTEST(rb_equal(args
[0], val
))) {
4164 args
[1] = rb_assoc_new(key
, val
);
4172 * hash.rassoc(value) -> new_array or nil
4174 * Returns a new 2-element Array consisting of the key and value
4175 * of the first-found entry whose value is <tt>==</tt> to value
4176 * (see {Entry Order}[rdoc-ref:Hash@Entry+Order]):
4177 * h = {foo: 0, bar: 1, baz: 1}
4178 * h.rassoc(1) # => [:bar, 1]
4180 * Returns +nil+ if no such value found.
4184 rb_hash_rassoc(VALUE hash
, VALUE obj
)
4190 rb_hash_foreach(hash
, rassoc_i
, (VALUE
)args
);
4195 flatten_i(VALUE key
, VALUE val
, VALUE ary
)
4201 rb_ary_cat(ary
, pair
, 2);
4208 * hash.flatten -> new_array
4209 * hash.flatten(level) -> new_array
4211 * Returns a new Array object that is a 1-dimensional flattening of +self+.
4215 * By default, nested Arrays are not flattened:
4216 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4217 * h.flatten # => [:foo, 0, :bar, [:bat, 3], :baz, 2]
4219 * Takes the depth of recursive flattening from Integer argument +level+:
4220 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4221 * h.flatten(1) # => [:foo, 0, :bar, [:bat, [:baz, [:bat]]]]
4222 * h.flatten(2) # => [:foo, 0, :bar, :bat, [:baz, [:bat]]]
4223 * h.flatten(3) # => [:foo, 0, :bar, :bat, :baz, [:bat]]
4224 * h.flatten(4) # => [:foo, 0, :bar, :bat, :baz, :bat]
4226 * When +level+ is negative, flattens all nested Arrays:
4227 * h = {foo: 0, bar: [:bat, [:baz, [:bat, ]]]}
4228 * h.flatten(-1) # => [:foo, 0, :bar, :bat, :baz, :bat]
4229 * h.flatten(-2) # => [:foo, 0, :bar, :bat, :baz, :bat]
4231 * When +level+ is zero, returns the equivalent of #to_a :
4232 * h = {foo: 0, bar: [:bat, 3], baz: 2}
4233 * h.flatten(0) # => [[:foo, 0], [:bar, [:bat, 3]], [:baz, 2]]
4234 * h.flatten(0) == h.to_a # => true
4238 rb_hash_flatten(int argc
, VALUE
*argv
, VALUE hash
)
4242 rb_check_arity(argc
, 0, 1);
4245 int level
= NUM2INT(argv
[0]);
4247 if (level
== 0) return rb_hash_to_a(hash
);
4249 ary
= rb_ary_new_capa(RHASH_SIZE(hash
) * 2);
4250 rb_hash_foreach(hash
, flatten_i
, ary
);
4254 VALUE ary_flatten_level
= INT2FIX(level
);
4255 rb_funcallv(ary
, id_flatten_bang
, 1, &ary_flatten_level
);
4257 else if (level
< 0) {
4258 /* flatten recursively */
4259 rb_funcallv(ary
, id_flatten_bang
, 0, 0);
4263 ary
= rb_ary_new_capa(RHASH_SIZE(hash
) * 2);
4264 rb_hash_foreach(hash
, flatten_i
, ary
);
4271 delete_if_nil(VALUE key
, VALUE value
, VALUE hash
)
4281 * hash.compact -> new_hash
4283 * Returns a copy of +self+ with all +nil+-valued entries removed:
4284 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4286 * h1 # => {:foo=>0, :baz=>2}
4290 rb_hash_compact(VALUE hash
)
4292 VALUE result
= rb_hash_dup(hash
);
4293 if (!RHASH_EMPTY_P(hash
)) {
4294 rb_hash_foreach(result
, delete_if_nil
, result
);
4295 compact_after_delete(result
);
4297 else if (rb_hash_compare_by_id_p(hash
)) {
4298 result
= rb_hash_compare_by_id(result
);
4305 * hash.compact! -> self or nil
4307 * Returns +self+ with all its +nil+-valued entries removed (in place):
4308 * h = {foo: 0, bar: nil, baz: 2, bat: nil}
4309 * h.compact! # => {:foo=>0, :baz=>2}
4311 * Returns +nil+ if no entries were removed.
4315 rb_hash_compact_bang(VALUE hash
)
4318 rb_hash_modify_check(hash
);
4319 n
= RHASH_SIZE(hash
);
4321 rb_hash_foreach(hash
, delete_if_nil
, hash
);
4322 if (n
!= RHASH_SIZE(hash
))
4330 * hash.compare_by_identity -> self
4332 * Sets +self+ to consider only identity in comparing keys;
4333 * two keys are considered the same only if they are the same object;
4336 * By default, these two object are considered to be the same key,
4337 * so +s1+ will overwrite +s0+:
4341 * h.compare_by_identity? # => false
4346 * After calling \#compare_by_identity, the keys are considered to be different,
4347 * and therefore do not overwrite each other:
4349 * h.compare_by_identity # => {}
4350 * h.compare_by_identity? # => true
4353 * h # => {"x"=>0, "x"=>1}
4357 rb_hash_compare_by_id(VALUE hash
)
4360 st_table
*identtable
;
4362 if (rb_hash_compare_by_id_p(hash
)) return hash
;
4364 rb_hash_modify_check(hash
);
4365 if (hash_iterating_p(hash
)) {
4366 rb_raise(rb_eRuntimeError
, "compare_by_identity during iteration");
4369 if (RHASH_TABLE_EMPTY_P(hash
)) {
4370 // Fast path: There's nothing to rehash, so we don't need a `tmp` table.
4371 // We're most likely an AR table, so this will need an allocation.
4372 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
4373 HASH_ASSERT(RHASH_ST_TABLE_P(hash
));
4375 RHASH_ST_TABLE(hash
)->type
= &identhash
;
4378 // Slow path: Need to rehash the members of `self` into a new
4379 // `tmp` table using the new `identhash` compare/hash functions.
4380 tmp
= hash_alloc(0);
4381 hash_st_table_init(tmp
, &identhash
, RHASH_SIZE(hash
));
4382 identtable
= RHASH_ST_TABLE(tmp
);
4384 rb_hash_foreach(hash
, rb_hash_rehash_i
, (VALUE
)tmp
);
4387 // We know for sure `identtable` is an st table,
4388 // so we can skip `ar_force_convert_table` here.
4389 RHASH_ST_TABLE_SET(hash
, identtable
);
4390 RHASH_ST_CLEAR(tmp
);
4398 * hash.compare_by_identity? -> true or false
4400 * Returns +true+ if #compare_by_identity has been called, +false+ otherwise.
4404 rb_hash_compare_by_id_p(VALUE hash
)
4406 return RBOOL(RHASH_IDENTHASH_P(hash
));
4410 rb_ident_hash_new(void)
4412 VALUE hash
= rb_hash_new();
4413 hash_st_table_init(hash
, &identhash
, 0);
4418 rb_ident_hash_new_with_size(st_index_t size
)
4420 VALUE hash
= rb_hash_new();
4421 hash_st_table_init(hash
, &identhash
, size
);
4426 rb_init_identtable(void)
4428 return st_init_table(&identhash
);
4432 any_p_i(VALUE key
, VALUE value
, VALUE arg
)
4434 VALUE ret
= rb_yield(rb_assoc_new(key
, value
));
4436 *(VALUE
*)arg
= Qtrue
;
4443 any_p_i_fast(VALUE key
, VALUE value
, VALUE arg
)
4445 VALUE ret
= rb_yield_values(2, key
, value
);
4447 *(VALUE
*)arg
= Qtrue
;
4454 any_p_i_pattern(VALUE key
, VALUE value
, VALUE arg
)
4456 VALUE ret
= rb_funcall(((VALUE
*)arg
)[1], idEqq
, 1, rb_assoc_new(key
, value
));
4458 *(VALUE
*)arg
= Qtrue
;
4466 * hash.any? -> true or false
4467 * hash.any?(object) -> true or false
4468 * hash.any? {|key, value| ... } -> true or false
4470 * Returns +true+ if any element satisfies a given criterion;
4471 * +false+ otherwise.
4473 * If +self+ has no element, returns +false+ and argument or block
4476 * With no argument and no block,
4477 * returns +true+ if +self+ is non-empty; +false+ if empty.
4479 * With argument +object+ and no block,
4480 * returns +true+ if for any key +key+
4481 * <tt>h.assoc(key) == object</tt>:
4482 * h = {foo: 0, bar: 1, baz: 2}
4483 * h.any?([:bar, 1]) # => true
4484 * h.any?([:bar, 0]) # => false
4485 * h.any?([:baz, 1]) # => false
4487 * With no argument and a block,
4488 * calls the block with each key-value pair;
4489 * returns +true+ if the block returns any truthy value,
4490 * +false+ otherwise:
4491 * h = {foo: 0, bar: 1, baz: 2}
4492 * h.any? {|key, value| value < 3 } # => true
4493 * h.any? {|key, value| value > 3 } # => false
4495 * Related: Enumerable#any?
4499 rb_hash_any_p(int argc
, VALUE
*argv
, VALUE hash
)
4504 rb_check_arity(argc
, 0, 1);
4505 if (RHASH_EMPTY_P(hash
)) return Qfalse
;
4507 if (rb_block_given_p()) {
4508 rb_warn("given block not used");
4512 rb_hash_foreach(hash
, any_p_i_pattern
, (VALUE
)args
);
4515 if (!rb_block_given_p()) {
4516 /* yields pairs, never false */
4519 if (rb_block_pair_yield_optimizable())
4520 rb_hash_foreach(hash
, any_p_i_fast
, (VALUE
)args
);
4522 rb_hash_foreach(hash
, any_p_i
, (VALUE
)args
);
4529 * hash.dig(key, *identifiers) -> object
4531 * Finds and returns the object in nested objects
4532 * that is specified by +key+ and +identifiers+.
4533 * The nested objects may be instances of various classes.
4534 * See {Dig Methods}[rdoc-ref:dig_methods.rdoc].
4537 * h = {foo: {bar: {baz: 2}}}
4538 * h.dig(:foo) # => {:bar=>{:baz=>2}}
4539 * h.dig(:foo, :bar) # => {:baz=>2}
4540 * h.dig(:foo, :bar, :baz) # => 2
4541 * h.dig(:foo, :bar, :BAZ) # => nil
4543 * Nested Hashes and Arrays:
4544 * h = {foo: {bar: [:a, :b, :c]}}
4545 * h.dig(:foo, :bar, 2) # => :c
4547 * This method will use the {default values}[rdoc-ref:Hash@Default+Values]
4548 * for keys that are not present:
4549 * h = {foo: {bar: [:a, :b, :c]}}
4550 * h.dig(:hello) # => nil
4551 * h.default_proc = -> (hash, _key) { hash }
4552 * h.dig(:hello, :world) # => h
4553 * h.dig(:hello, :world, :foo, :bar, 2) # => :c
4557 rb_hash_dig(int argc
, VALUE
*argv
, VALUE self
)
4559 rb_check_arity(argc
, 1, UNLIMITED_ARGUMENTS
);
4560 self
= rb_hash_aref(self
, *argv
);
4561 if (!--argc
) return self
;
4563 return rb_obj_dig(argc
, argv
, self
, Qnil
);
4567 hash_le_i(VALUE key
, VALUE value
, VALUE arg
)
4569 VALUE
*args
= (VALUE
*)arg
;
4570 VALUE v
= rb_hash_lookup2(args
[0], key
, Qundef
);
4571 if (!UNDEF_P(v
) && rb_equal(value
, v
)) return ST_CONTINUE
;
4577 hash_le(VALUE hash1
, VALUE hash2
)
4582 rb_hash_foreach(hash1
, hash_le_i
, (VALUE
)args
);
4588 * hash <= other_hash -> true or false
4590 * Returns +true+ if +hash+ is a subset of +other_hash+, +false+ otherwise:
4591 * h1 = {foo: 0, bar: 1}
4592 * h2 = {foo: 0, bar: 1, baz: 2}
4593 * h1 <= h2 # => true
4594 * h2 <= h1 # => false
4595 * h1 <= h1 # => true
4598 rb_hash_le(VALUE hash
, VALUE other
)
4600 other
= to_hash(other
);
4601 if (RHASH_SIZE(hash
) > RHASH_SIZE(other
)) return Qfalse
;
4602 return hash_le(hash
, other
);
4607 * hash < other_hash -> true or false
4609 * Returns +true+ if +hash+ is a proper subset of +other_hash+, +false+ otherwise:
4610 * h1 = {foo: 0, bar: 1}
4611 * h2 = {foo: 0, bar: 1, baz: 2}
4613 * h2 < h1 # => false
4614 * h1 < h1 # => false
4617 rb_hash_lt(VALUE hash
, VALUE other
)
4619 other
= to_hash(other
);
4620 if (RHASH_SIZE(hash
) >= RHASH_SIZE(other
)) return Qfalse
;
4621 return hash_le(hash
, other
);
4626 * hash >= other_hash -> true or false
4628 * Returns +true+ if +hash+ is a superset of +other_hash+, +false+ otherwise:
4629 * h1 = {foo: 0, bar: 1, baz: 2}
4630 * h2 = {foo: 0, bar: 1}
4631 * h1 >= h2 # => true
4632 * h2 >= h1 # => false
4633 * h1 >= h1 # => true
4636 rb_hash_ge(VALUE hash
, VALUE other
)
4638 other
= to_hash(other
);
4639 if (RHASH_SIZE(hash
) < RHASH_SIZE(other
)) return Qfalse
;
4640 return hash_le(other
, hash
);
4645 * hash > other_hash -> true or false
4647 * Returns +true+ if +hash+ is a proper superset of +other_hash+, +false+ otherwise:
4648 * h1 = {foo: 0, bar: 1, baz: 2}
4649 * h2 = {foo: 0, bar: 1}
4651 * h2 > h1 # => false
4652 * h1 > h1 # => false
4655 rb_hash_gt(VALUE hash
, VALUE other
)
4657 other
= to_hash(other
);
4658 if (RHASH_SIZE(hash
) <= RHASH_SIZE(other
)) return Qfalse
;
4659 return hash_le(other
, hash
);
4663 hash_proc_call(RB_BLOCK_CALL_FUNC_ARGLIST(key
, hash
))
4665 rb_check_arity(argc
, 1, 1);
4666 return rb_hash_aref(hash
, *argv
);
4671 * hash.to_proc -> proc
4673 * Returns a Proc object that maps a key to its value:
4674 * h = {foo: 0, bar: 1, baz: 2}
4676 * proc.class # => Proc
4677 * proc.call(:foo) # => 0
4678 * proc.call(:bar) # => 1
4679 * proc.call(:nosuch) # => nil
4682 rb_hash_to_proc(VALUE hash
)
4684 return rb_func_lambda_new(hash_proc_call
, hash
, 1, 1);
4689 rb_hash_deconstruct_keys(VALUE hash
, VALUE keys
)
4695 add_new_i(st_data_t
*key
, st_data_t
*val
, st_data_t arg
, int existing
)
4697 VALUE
*args
= (VALUE
*)arg
;
4698 if (existing
) return ST_STOP
;
4699 RB_OBJ_WRITTEN(args
[0], Qundef
, (VALUE
)*key
);
4700 RB_OBJ_WRITE(args
[0], (VALUE
*)val
, args
[1]);
4705 * add +key+ to +val+ pair if +hash+ does not contain +key+.
4706 * returns non-zero if +key+ was contained.
4709 rb_hash_add_new_element(VALUE hash
, VALUE key
, VALUE val
)
4717 if (RHASH_AR_TABLE_P(hash
)) {
4718 ret
= ar_update(hash
, (st_data_t
)key
, add_new_i
, (st_data_t
)args
);
4722 ar_force_convert_table(hash
, __FILE__
, __LINE__
);
4725 tbl
= RHASH_TBL_RAW(hash
);
4726 return st_update(tbl
, (st_data_t
)key
, add_new_i
, (st_data_t
)args
);
4731 key_stringify(VALUE key
)
4733 return (rb_obj_class(key
) == rb_cString
&& !RB_OBJ_FROZEN(key
)) ?
4734 rb_hash_key_str(key
) : key
;
4738 ar_bulk_insert(VALUE hash
, long argc
, const VALUE
*argv
)
4741 for (i
= 0; i
< argc
; ) {
4742 st_data_t k
= key_stringify(argv
[i
++]);
4743 st_data_t v
= argv
[i
++];
4744 ar_insert(hash
, k
, v
);
4745 RB_OBJ_WRITTEN(hash
, Qundef
, k
);
4746 RB_OBJ_WRITTEN(hash
, Qundef
, v
);
4751 rb_hash_bulk_insert(long argc
, const VALUE
*argv
, VALUE hash
)
4753 HASH_ASSERT(argc
% 2 == 0);
4755 st_index_t size
= argc
/ 2;
4757 if (RHASH_AR_TABLE_P(hash
) &&
4758 (RHASH_AR_TABLE_SIZE(hash
) + size
<= RHASH_AR_TABLE_MAX_SIZE
)) {
4759 ar_bulk_insert(hash
, argc
, argv
);
4762 rb_hash_bulk_insert_into_st_table(argc
, argv
, hash
);
4767 static char **origenviron
;
4769 #define GET_ENVIRON(e) ((e) = rb_w32_get_environ())
4770 #define FREE_ENVIRON(e) rb_w32_free_environ(e)
4771 static char **my_environ
;
4773 #define environ my_environ
4775 #define getenv(n) rb_w32_ugetenv(n)
4776 #elif defined(__APPLE__)
4778 #define environ (*_NSGetEnviron())
4779 #define GET_ENVIRON(e) (e)
4780 #define FREE_ENVIRON(e)
4782 extern char **environ
;
4783 #define GET_ENVIRON(e) (e)
4784 #define FREE_ENVIRON(e)
4786 #ifdef ENV_IGNORECASE
4787 #define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
4788 #define ENVNMATCH(s1, s2, n) (STRNCASECMP((s1), (s2), (n)) == 0)
4790 #define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
4791 #define ENVNMATCH(s1, s2, n) (memcmp((s1), (s2), (n)) == 0)
4794 #define ENV_LOCK() RB_VM_LOCK_ENTER()
4795 #define ENV_UNLOCK() RB_VM_LOCK_LEAVE()
4797 static inline rb_encoding
*
4801 return rb_utf8_encoding();
4803 return rb_locale_encoding();
4808 env_enc_str_new(const char *ptr
, long len
, rb_encoding
*enc
)
4810 VALUE str
= rb_external_str_new_with_enc(ptr
, len
, enc
);
4817 env_str_new(const char *ptr
, long len
)
4819 return env_enc_str_new(ptr
, len
, env_encoding());
4823 env_str_new2(const char *ptr
)
4825 if (!ptr
) return Qnil
;
4826 return env_str_new(ptr
, strlen(ptr
));
4830 getenv_with_lock(const char *name
)
4835 const char *val
= getenv(name
);
4836 ret
= env_str_new2(val
);
4843 has_env_with_lock(const char *name
)
4853 return val
? true : false;
4856 static const char TZ_ENV
[] = "TZ";
4859 get_env_cstr(VALUE str
, const char *name
)
4862 rb_encoding
*enc
= rb_enc_get(str
);
4863 if (!rb_enc_asciicompat(enc
)) {
4864 rb_raise(rb_eArgError
, "bad environment variable %s: ASCII incompatible encoding: %s",
4865 name
, rb_enc_name(enc
));
4867 var
= RSTRING_PTR(str
);
4868 if (memchr(var
, '\0', RSTRING_LEN(str
))) {
4869 rb_raise(rb_eArgError
, "bad environment variable %s: contains null byte", name
);
4871 return rb_str_fill_terminator(str
, 1); /* ASCII compatible */
4874 #define get_env_ptr(var, val) \
4875 (var = get_env_cstr(val, #var))
4877 static inline const char *
4878 env_name(volatile VALUE
*s
)
4882 get_env_ptr(name
, *s
);
4886 #define env_name(s) env_name(&(s))
4888 static VALUE
env_aset(VALUE nm
, VALUE val
);
4891 reset_by_modified_env(const char *nam
)
4894 * ENV['TZ'] = nil has a special meaning.
4895 * TZ is no longer considered up-to-date and ruby call tzset() as needed.
4896 * It could be useful if sysadmin change /etc/localtime.
4897 * This hack might works only on Linux glibc.
4899 if (ENVMATCH(nam
, TZ_ENV
)) {
4900 ruby_reset_timezone();
4905 env_delete(VALUE name
)
4907 const char *nam
= env_name(name
);
4908 reset_by_modified_env(nam
);
4909 VALUE val
= getenv_with_lock(nam
);
4912 ruby_setenv(nam
, 0);
4919 * ENV.delete(name) -> value
4920 * ENV.delete(name) { |name| block } -> value
4921 * ENV.delete(missing_name) -> nil
4922 * ENV.delete(missing_name) { |name| block } -> block_value
4924 * Deletes the environment variable with +name+ if it exists and returns its value:
4926 * ENV.delete('foo') # => '0'
4928 * If a block is not given and the named environment variable does not exist, returns +nil+.
4930 * If a block given and the environment variable does not exist,
4931 * yields +name+ to the block and returns the value of the block:
4932 * ENV.delete('foo') { |name| name * 2 } # => "foofoo"
4934 * If a block given and the environment variable exists,
4935 * deletes the environment variable and returns its value (ignoring the block):
4937 * ENV.delete('foo') { |name| raise 'ignored' } # => "0"
4939 * Raises an exception if +name+ is invalid.
4940 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
4943 env_delete_m(VALUE obj
, VALUE name
)
4947 val
= env_delete(name
);
4948 if (NIL_P(val
) && rb_block_given_p()) val
= rb_yield(name
);
4954 * ENV[name] -> value
4956 * Returns the value for the environment variable +name+ if it exists:
4958 * ENV['foo'] # => "0"
4959 * Returns +nil+ if the named variable does not exist.
4961 * Raises an exception if +name+ is invalid.
4962 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
4965 rb_f_getenv(VALUE obj
, VALUE name
)
4967 const char *nam
= env_name(name
);
4968 VALUE env
= getenv_with_lock(nam
);
4974 * ENV.fetch(name) -> value
4975 * ENV.fetch(name, default) -> value
4976 * ENV.fetch(name) { |name| block } -> value
4978 * If +name+ is the name of an environment variable, returns its value:
4980 * ENV.fetch('foo') # => '0'
4981 * Otherwise if a block is given (but not a default value),
4982 * yields +name+ to the block and returns the block's return value:
4983 * ENV.fetch('foo') { |name| :need_not_return_a_string } # => :need_not_return_a_string
4984 * Otherwise if a default value is given (but not a block), returns the default value:
4986 * ENV.fetch('foo', :default_need_not_be_a_string) # => :default_need_not_be_a_string
4987 * If the environment variable does not exist and both default and block are given,
4988 * issues a warning ("warning: block supersedes default value argument"),
4989 * yields +name+ to the block, and returns the block's return value:
4990 * ENV.fetch('foo', :default) { |name| :block_return } # => :block_return
4991 * Raises KeyError if +name+ is valid, but not found,
4992 * and neither default value nor block is given:
4993 * ENV.fetch('foo') # Raises KeyError (key not found: "foo")
4994 * Raises an exception if +name+ is invalid.
4995 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
4998 env_fetch(int argc
, VALUE
*argv
, VALUE _
)
5005 rb_check_arity(argc
, 1, 2);
5007 block_given
= rb_block_given_p();
5008 if (block_given
&& argc
== 2) {
5009 rb_warn("block supersedes default value argument");
5011 nam
= env_name(key
);
5012 env
= getenv_with_lock(nam
);
5015 if (block_given
) return rb_yield(key
);
5017 rb_key_err_raise(rb_sprintf("key not found: \"%"PRIsVALUE
"\"", key
), envtbl
, key
);
5024 #if defined(_WIN32) || (defined(HAVE_SETENV) && defined(HAVE_UNSETENV))
5027 in_origenv(const char *str
)
5030 for (env
= origenviron
; *env
; ++env
) {
5031 if (*env
== str
) return 1;
5037 envix(const char *nam
)
5041 register int i
, len
= strlen(nam
);
5044 env
= GET_ENVIRON(environ
);
5045 for (i
= 0; env
[i
]; i
++) {
5046 if (ENVNMATCH(env
[i
],nam
,len
) && env
[i
][len
] == '=')
5047 break; /* memcmp must come first to avoid */
5048 } /* potential SEGV's */
5049 FREE_ENVIRON(environ
);
5056 getenvsize(const WCHAR
* p
)
5058 const WCHAR
* porg
= p
;
5059 while (*p
++) p
+= lstrlenW(p
) + 1;
5060 return p
- porg
+ 1;
5064 getenvblocksize(void)
5074 check_envsize(size_t n
)
5076 if (_WIN32_WINNT
< 0x0600 && rb_w32_osver() < 6) {
5077 /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653(v=vs.85).aspx */
5078 /* Windows Server 2003 and Windows XP: The maximum size of the
5079 * environment block for the process is 32,767 characters. */
5080 WCHAR
* p
= GetEnvironmentStringsW();
5081 if (!p
) return -1; /* never happen */
5083 FreeEnvironmentStringsW(p
);
5084 if (n
>= getenvblocksize()) {
5092 #if defined(_WIN32) || \
5093 (defined(__sun) && !(defined(HAVE_SETENV) && defined(HAVE_UNSETENV)))
5095 NORETURN(static void invalid_envname(const char *name
));
5098 invalid_envname(const char *name
)
5100 rb_syserr_fail_str(EINVAL
, rb_sprintf("ruby_setenv(%s)", name
));
5104 check_envname(const char *name
)
5106 if (strchr(name
, '=')) {
5107 invalid_envname(name
);
5114 ruby_setenv(const char *name
, const char *value
)
5117 # if defined(MINGW_HAS_SECURE_API) || RUBY_MSVCRT_VERSION >= 80
5118 # define HAVE__WPUTENV_S 1
5125 check_envname(name
);
5126 len
= MultiByteToWideChar(CP_UTF8
, 0, name
, -1, NULL
, 0);
5129 len2
= MultiByteToWideChar(CP_UTF8
, 0, value
, -1, NULL
, 0);
5130 if (check_envsize((size_t)len
+ len2
)) { /* len and len2 include '\0' */
5131 goto fail
; /* 2 for '=' & '\0' */
5133 wname
= ALLOCV_N(WCHAR
, buf
, len
+ len2
);
5134 wvalue
= wname
+ len
;
5135 MultiByteToWideChar(CP_UTF8
, 0, name
, -1, wname
, len
);
5136 MultiByteToWideChar(CP_UTF8
, 0, value
, -1, wvalue
, len2
);
5137 #ifndef HAVE__WPUTENV_S
5138 wname
[len
-1] = L
'=';
5142 wname
= ALLOCV_N(WCHAR
, buf
, len
+ 1);
5143 MultiByteToWideChar(CP_UTF8
, 0, name
, -1, wname
, len
);
5144 wvalue
= wname
+ len
;
5146 #ifndef HAVE__WPUTENV_S
5147 wname
[len
-1] = L
'=';
5153 #ifndef HAVE__WPUTENV_S
5154 failed
= _wputenv(wname
);
5156 failed
= _wputenv_s(wname
, wvalue
);
5162 /* even if putenv() failed, clean up and try to delete the
5163 * variable from the system area. */
5164 if (!value
|| !*value
) {
5165 /* putenv() doesn't handle empty value */
5166 if (!SetEnvironmentVariable(name
, value
) &&
5167 GetLastError() != ERROR_ENVVAR_NOT_FOUND
) goto fail
;
5171 invalid_envname(name
);
5173 #elif defined(HAVE_SETENV) && defined(HAVE_UNSETENV)
5178 ret
= setenv(name
, value
, 1);
5182 if (ret
) rb_sys_fail_sprintf("setenv(%s)", name
);
5185 #ifdef VOID_UNSETENV
5195 ret
= unsetenv(name
);
5199 if (ret
) rb_sys_fail_sprintf("unsetenv(%s)", name
);
5203 /* Solaris 9 (or earlier) does not have setenv(3C) and unsetenv(3C). */
5204 /* The below code was tested on Solaris 10 by:
5205 % ./configure ac_cv_func_setenv=no ac_cv_func_unsetenv=no
5207 size_t len
, mem_size
;
5208 char **env_ptr
, *str
, *mem_ptr
;
5210 check_envname(name
);
5213 mem_size
= len
+ strlen(value
) + 2;
5214 mem_ptr
= malloc(mem_size
);
5215 if (mem_ptr
== NULL
)
5216 rb_sys_fail_sprintf("malloc(%"PRIuSIZE
")", mem_size
);
5217 snprintf(mem_ptr
, mem_size
, "%s=%s", name
, value
);
5222 for (env_ptr
= GET_ENVIRON(environ
); (str
= *env_ptr
) != 0; ++env_ptr
) {
5223 if (!strncmp(str
, name
, len
) && str
[len
] == '=') {
5224 if (!in_origenv(str
)) free(str
);
5225 while ((env_ptr
[0] = env_ptr
[1]) != 0) env_ptr
++;
5236 ret
= putenv(mem_ptr
);
5242 rb_sys_fail_sprintf("putenv(%s)", name
);
5251 i
= envix(name
); /* where does it go? */
5253 if (environ
== origenviron
) { /* need we copy environment? */
5258 for (max
= i
; environ
[max
]; max
++) ;
5259 tmpenv
= ALLOC_N(char*, max
+2);
5260 for (j
=0; j
<max
; j
++) /* copy environment */
5261 tmpenv
[j
] = ruby_strdup(environ
[j
]);
5263 environ
= tmpenv
; /* tell exec where it is now */
5267 char **envp
= origenviron
;
5268 while (*envp
&& *envp
!= environ
[i
]) envp
++;
5272 while (environ
[i
]) {
5273 environ
[i
] = environ
[i
+1];
5279 else { /* does not exist yet */
5280 if (!value
) goto finish
;
5281 REALLOC_N(environ
, char*, i
+2); /* just expand it a bit */
5282 environ
[i
+1] = 0; /* make sure it's null terminated */
5285 len
= strlen(name
) + strlen(value
) + 2;
5286 environ
[i
] = ALLOC_N(char, len
);
5287 snprintf(environ
[i
],len
,"%s=%s",name
,value
); /* all that work just for this */
5296 ruby_unsetenv(const char *name
)
5298 ruby_setenv(name
, 0);
5303 * ENV[name] = value -> value
5304 * ENV.store(name, value) -> value
5306 * Creates, updates, or deletes the named environment variable, returning the value.
5307 * Both +name+ and +value+ may be instances of String.
5308 * See {Valid Names and Values}[rdoc-ref:ENV@Valid+Names+and+Values].
5310 * - If the named environment variable does not exist:
5311 * - If +value+ is +nil+, does nothing.
5313 * ENV['foo'] = nil # => nil
5314 * ENV.include?('foo') # => false
5315 * ENV.store('bar', nil) # => nil
5316 * ENV.include?('bar') # => false
5317 * - If +value+ is not +nil+, creates the environment variable with +name+ and +value+:
5318 * # Create 'foo' using ENV.[]=.
5319 * ENV['foo'] = '0' # => '0'
5320 * ENV['foo'] # => '0'
5321 * # Create 'bar' using ENV.store.
5322 * ENV.store('bar', '1') # => '1'
5323 * ENV['bar'] # => '1'
5324 * - If the named environment variable exists:
5325 * - If +value+ is not +nil+, updates the environment variable with value +value+:
5326 * # Update 'foo' using ENV.[]=.
5327 * ENV['foo'] = '2' # => '2'
5328 * ENV['foo'] # => '2'
5329 * # Update 'bar' using ENV.store.
5330 * ENV.store('bar', '3') # => '3'
5331 * ENV['bar'] # => '3'
5332 * - If +value+ is +nil+, deletes the environment variable:
5333 * # Delete 'foo' using ENV.[]=.
5334 * ENV['foo'] = nil # => nil
5335 * ENV.include?('foo') # => false
5336 * # Delete 'bar' using ENV.store.
5337 * ENV.store('bar', nil) # => nil
5338 * ENV.include?('bar') # => false
5340 * Raises an exception if +name+ or +value+ is invalid.
5341 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5344 env_aset_m(VALUE obj
, VALUE nm
, VALUE val
)
5346 return env_aset(nm
, val
);
5350 env_aset(VALUE nm
, VALUE val
)
5360 /* nm can be modified in `val.to_str`, don't get `name` before
5361 * check for `val` */
5362 get_env_ptr(name
, nm
);
5363 get_env_ptr(value
, val
);
5365 ruby_setenv(name
, value
);
5366 reset_by_modified_env(name
);
5373 rb_encoding
*enc
= raw
? 0 : rb_locale_encoding();
5374 VALUE ary
= rb_ary_new();
5378 char **env
= GET_ENVIRON(environ
);
5380 char *s
= strchr(*env
, '=');
5382 const char *p
= *env
;
5384 VALUE e
= raw
? rb_utf8_str_new(p
, l
) : env_enc_str_new(p
, l
, enc
);
5385 rb_ary_push(ary
, e
);
5389 FREE_ENVIRON(environ
);
5398 * ENV.keys -> array of names
5400 * Returns all variable names in an Array:
5401 * ENV.replace('foo' => '0', 'bar' => '1')
5402 * ENV.keys # => ['bar', 'foo']
5403 * The order of the names is OS-dependent.
5404 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5406 * Returns the empty Array if ENV is empty.
5412 return env_keys(FALSE
);
5416 rb_env_size(VALUE ehash
, VALUE args
, VALUE eobj
)
5423 env
= GET_ENVIRON(environ
);
5424 for (; *env
; ++env
) {
5425 if (strchr(*env
, '=')) {
5429 FREE_ENVIRON(environ
);
5433 return LONG2FIX(cnt
);
5438 * ENV.each_key { |name| block } -> ENV
5439 * ENV.each_key -> an_enumerator
5441 * Yields each environment variable name:
5442 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5444 * ENV.each_key { |name| names.push(name) } # => ENV
5445 * names # => ["bar", "foo"]
5447 * Returns an Enumerator if no block given:
5448 * e = ENV.each_key # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_key>
5450 * e.each { |name| names.push(name) } # => ENV
5451 * names # => ["bar", "foo"]
5454 env_each_key(VALUE ehash
)
5459 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5460 keys
= env_keys(FALSE
);
5461 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5462 rb_yield(RARRAY_AREF(keys
, i
));
5470 VALUE ary
= rb_ary_new();
5474 char **env
= GET_ENVIRON(environ
);
5477 char *s
= strchr(*env
, '=');
5479 rb_ary_push(ary
, env_str_new2(s
+1));
5483 FREE_ENVIRON(environ
);
5492 * ENV.values -> array of values
5494 * Returns all environment variable values in an Array:
5495 * ENV.replace('foo' => '0', 'bar' => '1')
5496 * ENV.values # => ['1', '0']
5497 * The order of the values is OS-dependent.
5498 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
5500 * Returns the empty Array if ENV is empty.
5503 env_f_values(VALUE _
)
5505 return env_values();
5510 * ENV.each_value { |value| block } -> ENV
5511 * ENV.each_value -> an_enumerator
5513 * Yields each environment variable value:
5514 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
5516 * ENV.each_value { |value| values.push(value) } # => ENV
5517 * values # => ["1", "0"]
5519 * Returns an Enumerator if no block given:
5520 * e = ENV.each_value # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_value>
5522 * e.each { |value| values.push(value) } # => ENV
5523 * values # => ["1", "0"]
5526 env_each_value(VALUE ehash
)
5531 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5532 values
= env_values();
5533 for (i
=0; i
<RARRAY_LEN(values
); i
++) {
5534 rb_yield(RARRAY_AREF(values
, i
));
5541 * ENV.each { |name, value| block } -> ENV
5542 * ENV.each -> an_enumerator
5543 * ENV.each_pair { |name, value| block } -> ENV
5544 * ENV.each_pair -> an_enumerator
5546 * Yields each environment variable name and its value as a 2-element Array:
5548 * ENV.each_pair { |name, value| h[name] = value } # => ENV
5549 * h # => {"bar"=>"1", "foo"=>"0"}
5551 * Returns an Enumerator if no block given:
5553 * e = ENV.each_pair # => #<Enumerator: {"bar"=>"1", "foo"=>"0"}:each_pair>
5554 * e.each { |name, value| h[name] = value } # => ENV
5555 * h # => {"bar"=>"1", "foo"=>"0"}
5558 env_each_pair(VALUE ehash
)
5562 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5564 VALUE ary
= rb_ary_new();
5568 char **env
= GET_ENVIRON(environ
);
5571 char *s
= strchr(*env
, '=');
5573 rb_ary_push(ary
, env_str_new(*env
, s
-*env
));
5574 rb_ary_push(ary
, env_str_new2(s
+1));
5578 FREE_ENVIRON(environ
);
5582 if (rb_block_pair_yield_optimizable()) {
5583 for (i
=0; i
<RARRAY_LEN(ary
); i
+=2) {
5584 rb_yield_values(2, RARRAY_AREF(ary
, i
), RARRAY_AREF(ary
, i
+1));
5588 for (i
=0; i
<RARRAY_LEN(ary
); i
+=2) {
5589 rb_yield(rb_assoc_new(RARRAY_AREF(ary
, i
), RARRAY_AREF(ary
, i
+1)));
5598 * ENV.reject! { |name, value| block } -> ENV or nil
5599 * ENV.reject! -> an_enumerator
5601 * Similar to ENV.delete_if, but returns +nil+ if no changes were made.
5603 * Yields each environment variable name and its value as a 2-element Array,
5604 * deleting each environment variable for which the block returns a truthy value,
5605 * and returning ENV (if any deletions) or +nil+ (if not):
5606 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5607 * ENV.reject! { |name, value| name.start_with?('b') } # => ENV
5608 * ENV # => {"foo"=>"0"}
5609 * ENV.reject! { |name, value| name.start_with?('b') } # => nil
5611 * Returns an Enumerator if no block given:
5612 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5613 * e = ENV.reject! # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:reject!>
5614 * e.each { |name, value| name.start_with?('b') } # => ENV
5615 * ENV # => {"foo"=>"0"}
5616 * e.each { |name, value| name.start_with?('b') } # => nil
5619 env_reject_bang(VALUE ehash
)
5625 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5626 keys
= env_keys(FALSE
);
5627 RBASIC_CLEAR_CLASS(keys
);
5628 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5629 VALUE val
= rb_f_getenv(Qnil
, RARRAY_AREF(keys
, i
));
5631 if (RTEST(rb_yield_values(2, RARRAY_AREF(keys
, i
), val
))) {
5632 env_delete(RARRAY_AREF(keys
, i
));
5638 if (del
== 0) return Qnil
;
5644 * ENV.delete_if { |name, value| block } -> ENV
5645 * ENV.delete_if -> an_enumerator
5647 * Yields each environment variable name and its value as a 2-element Array,
5648 * deleting each environment variable for which the block returns a truthy value,
5649 * and returning ENV (regardless of whether any deletions):
5650 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5651 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5652 * ENV # => {"foo"=>"0"}
5653 * ENV.delete_if { |name, value| name.start_with?('b') } # => ENV
5655 * Returns an Enumerator if no block given:
5656 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5657 * e = ENV.delete_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:delete_if!>
5658 * e.each { |name, value| name.start_with?('b') } # => ENV
5659 * ENV # => {"foo"=>"0"}
5660 * e.each { |name, value| name.start_with?('b') } # => ENV
5663 env_delete_if(VALUE ehash
)
5665 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5666 env_reject_bang(ehash
);
5672 * ENV.values_at(*names) -> array of values
5674 * Returns an Array containing the environment variable values associated with
5676 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5677 * ENV.values_at('foo', 'baz') # => ["0", "2"]
5679 * Returns +nil+ in the Array for each name that is not an ENV name:
5680 * ENV.values_at('foo', 'bat', 'bar', 'bam') # => ["0", nil, "1", nil]
5682 * Returns an empty Array if no names given.
5684 * Raises an exception if any name is invalid.
5685 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
5688 env_values_at(int argc
, VALUE
*argv
, VALUE _
)
5693 result
= rb_ary_new();
5694 for (i
=0; i
<argc
; i
++) {
5695 rb_ary_push(result
, rb_f_getenv(Qnil
, argv
[i
]));
5702 * ENV.select { |name, value| block } -> hash of name/value pairs
5703 * ENV.select -> an_enumerator
5704 * ENV.filter { |name, value| block } -> hash of name/value pairs
5705 * ENV.filter -> an_enumerator
5707 * Yields each environment variable name and its value as a 2-element Array,
5708 * returning a Hash of the names and values for which the block returns a truthy value:
5709 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5710 * ENV.select { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5711 * ENV.filter { |name, value| name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5713 * Returns an Enumerator if no block given:
5714 * e = ENV.select # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:select>
5715 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5716 * e = ENV.filter # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:filter>
5717 * e.each { |name, value | name.start_with?('b') } # => {"bar"=>"1", "baz"=>"2"}
5720 env_select(VALUE ehash
)
5726 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5727 result
= rb_hash_new();
5728 keys
= env_keys(FALSE
);
5729 for (i
= 0; i
< RARRAY_LEN(keys
); ++i
) {
5730 VALUE key
= RARRAY_AREF(keys
, i
);
5731 VALUE val
= rb_f_getenv(Qnil
, key
);
5733 if (RTEST(rb_yield_values(2, key
, val
))) {
5734 rb_hash_aset(result
, key
, val
);
5745 * ENV.select! { |name, value| block } -> ENV or nil
5746 * ENV.select! -> an_enumerator
5747 * ENV.filter! { |name, value| block } -> ENV or nil
5748 * ENV.filter! -> an_enumerator
5750 * Yields each environment variable name and its value as a 2-element Array,
5751 * deleting each entry for which the block returns +false+ or +nil+,
5752 * and returning ENV if any deletions made, or +nil+ otherwise:
5754 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5755 * ENV.select! { |name, value| name.start_with?('b') } # => ENV
5756 * ENV # => {"bar"=>"1", "baz"=>"2"}
5757 * ENV.select! { |name, value| true } # => nil
5759 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5760 * ENV.filter! { |name, value| name.start_with?('b') } # => ENV
5761 * ENV # => {"bar"=>"1", "baz"=>"2"}
5762 * ENV.filter! { |name, value| true } # => nil
5764 * Returns an Enumerator if no block given:
5766 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5767 * e = ENV.select! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:select!>
5768 * e.each { |name, value| name.start_with?('b') } # => ENV
5769 * ENV # => {"bar"=>"1", "baz"=>"2"}
5770 * e.each { |name, value| true } # => nil
5772 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5773 * e = ENV.filter! # => #<Enumerator: {"bar"=>"1", "baz"=>"2"}:filter!>
5774 * e.each { |name, value| name.start_with?('b') } # => ENV
5775 * ENV # => {"bar"=>"1", "baz"=>"2"}
5776 * e.each { |name, value| true } # => nil
5779 env_select_bang(VALUE ehash
)
5785 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5786 keys
= env_keys(FALSE
);
5787 RBASIC_CLEAR_CLASS(keys
);
5788 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5789 VALUE val
= rb_f_getenv(Qnil
, RARRAY_AREF(keys
, i
));
5791 if (!RTEST(rb_yield_values(2, RARRAY_AREF(keys
, i
), val
))) {
5792 env_delete(RARRAY_AREF(keys
, i
));
5798 if (del
== 0) return Qnil
;
5804 * ENV.keep_if { |name, value| block } -> ENV
5805 * ENV.keep_if -> an_enumerator
5807 * Yields each environment variable name and its value as a 2-element Array,
5808 * deleting each environment variable for which the block returns +false+ or +nil+,
5809 * and returning ENV:
5810 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5811 * ENV.keep_if { |name, value| name.start_with?('b') } # => ENV
5812 * ENV # => {"bar"=>"1", "baz"=>"2"}
5814 * Returns an Enumerator if no block given:
5815 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
5816 * e = ENV.keep_if # => #<Enumerator: {"bar"=>"1", "baz"=>"2", "foo"=>"0"}:keep_if>
5817 * e.each { |name, value| name.start_with?('b') } # => ENV
5818 * ENV # => {"bar"=>"1", "baz"=>"2"}
5821 env_keep_if(VALUE ehash
)
5823 RETURN_SIZED_ENUMERATOR(ehash
, 0, 0, rb_env_size
);
5824 env_select_bang(ehash
);
5830 * ENV.slice(*names) -> hash of name/value pairs
5832 * Returns a Hash of the given ENV names and their corresponding values:
5833 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2', 'bat' => '3')
5834 * ENV.slice('foo', 'baz') # => {"foo"=>"0", "baz"=>"2"}
5835 * ENV.slice('baz', 'foo') # => {"baz"=>"2", "foo"=>"0"}
5836 * Raises an exception if any of the +names+ is invalid
5837 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
5838 * ENV.slice('foo', 'bar', :bat) # Raises TypeError (no implicit conversion of Symbol into String)
5841 env_slice(int argc
, VALUE
*argv
, VALUE _
)
5844 VALUE key
, value
, result
;
5847 return rb_hash_new();
5849 result
= rb_hash_new_with_size(argc
);
5851 for (i
= 0; i
< argc
; i
++) {
5853 value
= rb_f_getenv(Qnil
, key
);
5855 rb_hash_aset(result
, key
, value
);
5867 keys
= env_keys(TRUE
);
5868 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
5869 VALUE key
= RARRAY_AREF(keys
, i
);
5870 const char *nam
= RSTRING_PTR(key
);
5871 ruby_setenv(nam
, 0);
5881 * Removes every environment variable; returns ENV:
5882 * ENV.replace('foo' => '0', 'bar' => '1')
5884 * ENV.clear # => ENV
5890 return rb_env_clear();
5897 * Returns String 'ENV':
5898 * ENV.to_s # => "ENV"
5903 return rb_usascii_str_new2("ENV");
5908 * ENV.inspect -> a_string
5910 * Returns the contents of the environment as a String:
5911 * ENV.replace('foo' => '0', 'bar' => '1')
5912 * ENV.inspect # => "{\"bar\"=>\"1\", \"foo\"=>\"0\"}"
5915 env_inspect(VALUE _
)
5918 VALUE str
= rb_str_buf_new2("{");
5922 char **env
= GET_ENVIRON(environ
);
5924 char *s
= strchr(*env
, '=');
5926 if (env
!= environ
) {
5927 rb_str_buf_cat2(str
, ", ");
5930 rb_str_buf_cat2(str
, "\"");
5931 rb_str_buf_cat(str
, *env
, s
-*env
);
5932 rb_str_buf_cat2(str
, "\"=>");
5933 i
= rb_inspect(rb_str_new2(s
+1));
5934 rb_str_buf_append(str
, i
);
5938 FREE_ENVIRON(environ
);
5942 rb_str_buf_cat2(str
, "}");
5949 * ENV.to_a -> array of 2-element arrays
5951 * Returns the contents of ENV as an Array of 2-element Arrays,
5952 * each of which is a name/value pair:
5953 * ENV.replace('foo' => '0', 'bar' => '1')
5954 * ENV.to_a # => [["bar", "1"], ["foo", "0"]]
5959 VALUE ary
= rb_ary_new();
5963 char **env
= GET_ENVIRON(environ
);
5965 char *s
= strchr(*env
, '=');
5967 rb_ary_push(ary
, rb_assoc_new(env_str_new(*env
, s
-*env
),
5968 env_str_new2(s
+1)));
5972 FREE_ENVIRON(environ
);
5983 * (Provided for compatibility with Hash.)
5985 * Does not modify ENV; returns +nil+.
5994 env_size_with_lock(void)
6000 char **env
= GET_ENVIRON(environ
);
6002 FREE_ENVIRON(environ
);
6011 * ENV.length -> an_integer
6012 * ENV.size -> an_integer
6014 * Returns the count of environment variables:
6015 * ENV.replace('foo' => '0', 'bar' => '1')
6022 return INT2FIX(env_size_with_lock());
6027 * ENV.empty? -> true or false
6029 * Returns +true+ when there are no environment variables, +false+ otherwise:
6031 * ENV.empty? # => true
6033 * ENV.empty? # => false
6036 env_empty_p(VALUE _
)
6042 char **env
= GET_ENVIRON(environ
);
6046 FREE_ENVIRON(environ
);
6050 return RBOOL(empty
);
6055 * ENV.include?(name) -> true or false
6056 * ENV.has_key?(name) -> true or false
6057 * ENV.member?(name) -> true or false
6058 * ENV.key?(name) -> true or false
6060 * Returns +true+ if there is an environment variable with the given +name+:
6061 * ENV.replace('foo' => '0', 'bar' => '1')
6062 * ENV.include?('foo') # => true
6063 * Returns +false+ if +name+ is a valid String and there is no such environment variable:
6064 * ENV.include?('baz') # => false
6065 * Returns +false+ if +name+ is the empty String or is a String containing character <code>'='</code>:
6066 * ENV.include?('') # => false
6067 * ENV.include?('=') # => false
6068 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6069 * ENV.include?("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6070 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6071 * ENV.include?("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6072 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6073 * Raises an exception if +name+ is not a String:
6074 * ENV.include?(Object.new) # TypeError (no implicit conversion of Object into String)
6077 env_has_key(VALUE env
, VALUE key
)
6079 const char *s
= env_name(key
);
6080 return RBOOL(has_env_with_lock(s
));
6085 * ENV.assoc(name) -> [name, value] or nil
6087 * Returns a 2-element Array containing the name and value of the environment variable
6088 * for +name+ if it exists:
6089 * ENV.replace('foo' => '0', 'bar' => '1')
6090 * ENV.assoc('foo') # => ['foo', '0']
6091 * Returns +nil+ if +name+ is a valid String and there is no such environment variable.
6093 * Returns +nil+ if +name+ is the empty String or is a String containing character <code>'='</code>.
6095 * Raises an exception if +name+ is a String containing the NUL character <code>"\0"</code>:
6096 * ENV.assoc("\0") # Raises ArgumentError (bad environment variable name: contains null byte)
6097 * Raises an exception if +name+ has an encoding that is not ASCII-compatible:
6098 * ENV.assoc("\xa1\xa1".force_encoding(Encoding::UTF_16LE))
6099 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: UTF-16LE)
6100 * Raises an exception if +name+ is not a String:
6101 * ENV.assoc(Object.new) # TypeError (no implicit conversion of Object into String)
6104 env_assoc(VALUE env
, VALUE key
)
6106 const char *s
= env_name(key
);
6107 VALUE e
= getenv_with_lock(s
);
6110 return rb_assoc_new(key
, e
);
6119 * ENV.value?(value) -> true or false
6120 * ENV.has_value?(value) -> true or false
6122 * Returns +true+ if +value+ is the value for some environment variable name, +false+ otherwise:
6123 * ENV.replace('foo' => '0', 'bar' => '1')
6124 * ENV.value?('0') # => true
6125 * ENV.has_value?('0') # => true
6126 * ENV.value?('2') # => false
6127 * ENV.has_value?('2') # => false
6130 env_has_value(VALUE dmy
, VALUE obj
)
6132 obj
= rb_check_string_type(obj
);
6133 if (NIL_P(obj
)) return Qnil
;
6139 char **env
= GET_ENVIRON(environ
);
6141 char *s
= strchr(*env
, '=');
6143 long len
= strlen(s
);
6144 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
6151 FREE_ENVIRON(environ
);
6160 * ENV.rassoc(value) -> [name, value] or nil
6162 * Returns a 2-element Array containing the name and value of the
6163 * *first* *found* environment variable that has value +value+, if one
6165 * ENV.replace('foo' => '0', 'bar' => '0')
6166 * ENV.rassoc('0') # => ["bar", "0"]
6167 * The order in which environment variables are examined is OS-dependent.
6168 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6170 * Returns +nil+ if there is no such environment variable.
6173 env_rassoc(VALUE dmy
, VALUE obj
)
6175 obj
= rb_check_string_type(obj
);
6176 if (NIL_P(obj
)) return Qnil
;
6178 VALUE result
= Qnil
;
6182 char **env
= GET_ENVIRON(environ
);
6185 const char *p
= *env
;
6186 char *s
= strchr(p
, '=');
6188 long len
= strlen(s
);
6189 if (RSTRING_LEN(obj
) == len
&& strncmp(s
, RSTRING_PTR(obj
), len
) == 0) {
6190 result
= rb_assoc_new(rb_str_new(p
, s
-p
-1), obj
);
6196 FREE_ENVIRON(environ
);
6205 * ENV.key(value) -> name or nil
6207 * Returns the name of the first environment variable with +value+, if it exists:
6208 * ENV.replace('foo' => '0', 'bar' => '0')
6209 * ENV.key('0') # => "foo"
6210 * The order in which environment variables are examined is OS-dependent.
6211 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6213 * Returns +nil+ if there is no such value.
6215 * Raises an exception if +value+ is invalid:
6216 * ENV.key(Object.new) # raises TypeError (no implicit conversion of Object into String)
6217 * See {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values].
6220 env_key(VALUE dmy
, VALUE value
)
6227 char **env
= GET_ENVIRON(environ
);
6229 char *s
= strchr(*env
, '=');
6231 long len
= strlen(s
);
6232 if (RSTRING_LEN(value
) == len
&& strncmp(s
, RSTRING_PTR(value
), len
) == 0) {
6233 str
= env_str_new(*env
, s
-*env
-1);
6239 FREE_ENVIRON(environ
);
6249 VALUE hash
= rb_hash_new();
6253 char **env
= GET_ENVIRON(environ
);
6255 char *s
= strchr(*env
, '=');
6257 rb_hash_aset(hash
, env_str_new(*env
, s
-*env
),
6262 FREE_ENVIRON(environ
);
6276 rb_env_to_hash(void)
6278 return env_to_hash();
6283 * ENV.to_hash -> hash of name/value pairs
6285 * Returns a Hash containing all name/value pairs from ENV:
6286 * ENV.replace('foo' => '0', 'bar' => '1')
6287 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6291 env_f_to_hash(VALUE _
)
6293 return env_to_hash();
6298 * ENV.to_h -> hash of name/value pairs
6299 * ENV.to_h {|name, value| block } -> hash of name/value pairs
6301 * With no block, returns a Hash containing all name/value pairs from ENV:
6302 * ENV.replace('foo' => '0', 'bar' => '1')
6303 * ENV.to_h # => {"bar"=>"1", "foo"=>"0"}
6304 * With a block, returns a Hash whose items are determined by the block.
6305 * Each name/value pair in ENV is yielded to the block.
6306 * The block must return a 2-element Array (name/value pair)
6307 * that is added to the return Hash as a key and value:
6308 * ENV.to_h { |name, value| [name.to_sym, value.to_i] } # => {:bar=>1, :foo=>0}
6309 * Raises an exception if the block does not return an Array:
6310 * ENV.to_h { |name, value| name } # Raises TypeError (wrong element type String (expected array))
6311 * Raises an exception if the block returns an Array of the wrong size:
6312 * ENV.to_h { |name, value| [name] } # Raises ArgumentError (element has wrong array length (expected 2, was 1))
6317 VALUE hash
= env_to_hash();
6318 if (rb_block_given_p()) {
6319 hash
= rb_hash_to_h_block(hash
);
6326 * ENV.except(*keys) -> a_hash
6328 * Returns a hash except the given keys from ENV and their values.
6330 * ENV #=> {"LANG"=>"en_US.UTF-8", "TERM"=>"xterm-256color", "HOME"=>"/Users/rhc"}
6331 * ENV.except("TERM","HOME") #=> {"LANG"=>"en_US.UTF-8"}
6334 env_except(int argc
, VALUE
*argv
, VALUE _
)
6337 VALUE key
, hash
= env_to_hash();
6339 for (i
= 0; i
< argc
; i
++) {
6341 rb_hash_delete(hash
, key
);
6349 * ENV.reject { |name, value| block } -> hash of name/value pairs
6350 * ENV.reject -> an_enumerator
6352 * Yields each environment variable name and its value as a 2-element Array.
6353 * Returns a Hash whose items are determined by the block.
6354 * When the block returns a truthy value, the name/value pair is added to the return Hash;
6355 * otherwise the pair is ignored:
6356 * ENV.replace('foo' => '0', 'bar' => '1', 'baz' => '2')
6357 * ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6358 * Returns an Enumerator if no block given:
6360 * e.each { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
6365 return rb_hash_delete_if(env_to_hash());
6368 NORETURN(static VALUE
env_freeze(VALUE self
));
6373 * Raises an exception:
6374 * ENV.freeze # Raises TypeError (cannot freeze ENV)
6377 env_freeze(VALUE self
)
6379 rb_raise(rb_eTypeError
, "cannot freeze ENV");
6380 UNREACHABLE_RETURN(self
);
6385 * ENV.shift -> [name, value] or nil
6387 * Removes the first environment variable from ENV and returns
6388 * a 2-element Array containing its name and value:
6389 * ENV.replace('foo' => '0', 'bar' => '1')
6390 * ENV.to_hash # => {'bar' => '1', 'foo' => '0'}
6391 * ENV.shift # => ['bar', '1']
6392 * ENV.to_hash # => {'foo' => '0'}
6393 * Exactly which environment variable is "first" is OS-dependent.
6394 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6396 * Returns +nil+ if the environment is empty.
6401 VALUE result
= Qnil
;
6406 char **env
= GET_ENVIRON(environ
);
6408 const char *p
= *env
;
6409 char *s
= strchr(p
, '=');
6411 key
= env_str_new(p
, s
-p
);
6412 VALUE val
= env_str_new2(getenv(RSTRING_PTR(key
)));
6413 result
= rb_assoc_new(key
, val
);
6416 FREE_ENVIRON(environ
);
6429 * ENV.invert -> hash of value/name pairs
6431 * Returns a Hash whose keys are the ENV values,
6432 * and whose values are the corresponding ENV names:
6433 * ENV.replace('foo' => '0', 'bar' => '1')
6434 * ENV.invert # => {"1"=>"bar", "0"=>"foo"}
6435 * For a duplicate ENV value, overwrites the hash entry:
6436 * ENV.replace('foo' => '0', 'bar' => '0')
6437 * ENV.invert # => {"0"=>"foo"}
6438 * Note that the order of the ENV processing is OS-dependent,
6439 * which means that the order of overwriting is also OS-dependent.
6440 * See {About Ordering}[rdoc-ref:ENV@About+Ordering].
6445 return rb_hash_invert(env_to_hash());
6449 keylist_delete(VALUE keys
, VALUE key
)
6452 const char *keyptr
, *eptr
;
6453 RSTRING_GETMEM(key
, keyptr
, keylen
);
6454 /* Don't stop at first key, as it is possible to have
6455 multiple environment values with the same key.
6457 for (long i
=0; i
<RARRAY_LEN(keys
); i
++) {
6458 VALUE e
= RARRAY_AREF(keys
, i
);
6459 RSTRING_GETMEM(e
, eptr
, elen
);
6460 if (elen
!= keylen
) continue;
6461 if (!ENVNMATCH(keyptr
, eptr
, elen
)) continue;
6462 rb_ary_delete_at(keys
, i
);
6468 env_replace_i(VALUE key
, VALUE val
, VALUE keys
)
6473 keylist_delete(keys
, key
);
6479 * ENV.replace(hash) -> ENV
6481 * Replaces the entire content of the environment variables
6482 * with the name/value pairs in the given +hash+;
6485 * Replaces the content of ENV with the given pairs:
6486 * ENV.replace('foo' => '0', 'bar' => '1') # => ENV
6487 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6489 * Raises an exception if a name or value is invalid
6490 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6491 * ENV.replace('foo' => '0', :bar => '1') # Raises TypeError (no implicit conversion of Symbol into String)
6492 * ENV.replace('foo' => '0', 'bar' => 1) # Raises TypeError (no implicit conversion of Integer into String)
6493 * ENV.to_hash # => {"bar"=>"1", "foo"=>"0"}
6496 env_replace(VALUE env
, VALUE hash
)
6501 keys
= env_keys(TRUE
);
6502 if (env
== hash
) return env
;
6503 hash
= to_hash(hash
);
6504 rb_hash_foreach(hash
, env_replace_i
, keys
);
6506 for (i
=0; i
<RARRAY_LEN(keys
); i
++) {
6507 env_delete(RARRAY_AREF(keys
, i
));
6514 env_update_i(VALUE key
, VALUE val
, VALUE _
)
6521 env_update_block_i(VALUE key
, VALUE val
, VALUE _
)
6523 VALUE oldval
= rb_f_getenv(Qnil
, key
);
6524 if (!NIL_P(oldval
)) {
6525 val
= rb_yield_values(3, key
, oldval
, val
);
6534 * ENV.update(*hashes) -> ENV
6535 * ENV.update(*hashes) { |name, env_val, hash_val| block } -> ENV
6537 * ENV.merge!(*hashes) -> ENV
6538 * ENV.merge!(*hashes) { |name, env_val, hash_val| block } -> ENV
6540 * Adds to ENV each key/value pair in the given +hash+; returns ENV:
6541 * ENV.replace('foo' => '0', 'bar' => '1')
6542 * ENV.merge!('baz' => '2', 'bat' => '3') # => {"bar"=>"1", "bat"=>"3", "baz"=>"2", "foo"=>"0"}
6543 * Deletes the ENV entry for a hash value that is +nil+:
6544 * ENV.merge!('baz' => nil, 'bat' => nil) # => {"bar"=>"1", "foo"=>"0"}
6545 * For an already-existing name, if no block given, overwrites the ENV value:
6546 * ENV.merge!('foo' => '4') # => {"bar"=>"1", "foo"=>"4"}
6547 * For an already-existing name, if block given,
6548 * yields the name, its ENV value, and its hash value;
6549 * the block's return value becomes the new name:
6550 * ENV.merge!('foo' => '5') { |name, env_val, hash_val | env_val + hash_val } # => {"bar"=>"1", "foo"=>"45"}
6551 * Raises an exception if a name or value is invalid
6552 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]);
6553 * ENV.replace('foo' => '0', 'bar' => '1')
6554 * ENV.merge!('foo' => '6', :bar => '7', 'baz' => '9') # Raises TypeError (no implicit conversion of Symbol into String)
6555 * ENV # => {"bar"=>"1", "foo"=>"6"}
6556 * ENV.merge!('foo' => '7', 'bar' => 8, 'baz' => '9') # Raises TypeError (no implicit conversion of Integer into String)
6557 * ENV # => {"bar"=>"1", "foo"=>"7"}
6558 * Raises an exception if the block returns an invalid name:
6559 * (see {Invalid Names and Values}[rdoc-ref:ENV@Invalid+Names+and+Values]):
6560 * ENV.merge!('bat' => '8', 'foo' => '9') { |name, env_val, hash_val | 10 } # Raises TypeError (no implicit conversion of Integer into String)
6561 * ENV # => {"bar"=>"1", "bat"=>"8", "foo"=>"7"}
6563 * Note that for the exceptions above,
6564 * hash pairs preceding an invalid name or value are processed normally;
6565 * those following are ignored.
6568 env_update(int argc
, VALUE
*argv
, VALUE env
)
6570 rb_foreach_func
*func
= rb_block_given_p() ?
6571 env_update_block_i
: env_update_i
;
6572 for (int i
= 0; i
< argc
; ++i
) {
6573 VALUE hash
= argv
[i
];
6574 if (env
== hash
) continue;
6575 hash
= to_hash(hash
);
6576 rb_hash_foreach(hash
, func
, 0);
6581 NORETURN(static VALUE
env_clone(int, VALUE
*, VALUE
));
6584 * ENV.clone(freeze: nil) # raises TypeError
6586 * Raises TypeError, because ENV is a wrapper for the process-wide
6587 * environment variables and a clone is useless.
6588 * Use #to_h to get a copy of ENV data as a hash.
6591 env_clone(int argc
, VALUE
*argv
, VALUE obj
)
6595 if (rb_scan_args(argc
, argv
, "0:", &opt
) < argc
) {
6596 rb_get_freeze_opt(1, &opt
);
6600 rb_raise(rb_eTypeError
, "Cannot clone ENV, use ENV.to_h to get a copy of ENV as a hash");
6603 NORETURN(static VALUE
env_dup(VALUE
));
6606 * ENV.dup # raises TypeError
6608 * Raises TypeError, because ENV is a singleton object.
6609 * Use #to_h to get a copy of ENV data as a hash.
6614 rb_raise(rb_eTypeError
, "Cannot dup ENV, use ENV.to_h to get a copy of ENV as a hash");
6617 static const rb_data_type_t env_data_type
= {
6625 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
| RUBY_TYPED_WB_PROTECTED
,
6629 * A +Hash+ maps each of its unique keys to a specific value.
6631 * A +Hash+ has certain similarities to an Array, but:
6632 * - An Array index is always an Integer.
6633 * - A +Hash+ key can be (almost) any object.
6635 * === +Hash+ \Data Syntax
6637 * The older syntax for +Hash+ data uses the "hash rocket," <tt>=></tt>:
6639 * h = {:foo => 0, :bar => 1, :baz => 2}
6640 * h # => {:foo=>0, :bar=>1, :baz=>2}
6642 * Alternatively, but only for a +Hash+ key that's a Symbol,
6643 * you can use a newer JSON-style syntax,
6644 * where each bareword becomes a Symbol:
6646 * h = {foo: 0, bar: 1, baz: 2}
6647 * h # => {:foo=>0, :bar=>1, :baz=>2}
6649 * You can also use a String in place of a bareword:
6651 * h = {'foo': 0, 'bar': 1, 'baz': 2}
6652 * h # => {:foo=>0, :bar=>1, :baz=>2}
6654 * And you can mix the styles:
6656 * h = {foo: 0, :bar => 1, 'baz': 2}
6657 * h # => {:foo=>0, :bar=>1, :baz=>2}
6659 * But it's an error to try the JSON-style syntax
6660 * for a key that's not a bareword or a String:
6662 * # Raises SyntaxError (syntax error, unexpected ':', expecting =>):
6665 * +Hash+ value can be omitted, meaning that value will be fetched from the context
6666 * by the name of the key:
6671 * h # => {:x=>0, :y=>100}
6675 * You can use a +Hash+ to give names to objects:
6677 * person = {name: 'Matz', language: 'Ruby'}
6678 * person # => {:name=>"Matz", :language=>"Ruby"}
6680 * You can use a +Hash+ to give names to method arguments:
6682 * def some_method(hash)
6685 * some_method({foo: 0, bar: 1, baz: 2}) # => {:foo=>0, :bar=>1, :baz=>2}
6687 * Note: when the last argument in a method call is a +Hash+,
6688 * the curly braces may be omitted:
6690 * some_method(foo: 0, bar: 1, baz: 2) # => {:foo=>0, :bar=>1, :baz=>2}
6692 * You can use a +Hash+ to initialize an object:
6695 * attr_accessor :name, :language
6696 * def initialize(hash)
6697 * self.name = hash[:name]
6698 * self.language = hash[:language]
6701 * matz = Dev.new(name: 'Matz', language: 'Ruby')
6702 * matz # => #<Dev: @name="Matz", @language="Ruby">
6704 * === Creating a +Hash+
6706 * You can create a +Hash+ object explicitly with:
6708 * - A {hash literal}[rdoc-ref:syntax/literals.rdoc@Hash+Literals].
6710 * You can convert certain objects to Hashes with:
6714 * You can create a +Hash+ by calling method Hash.new.
6716 * Create an empty +Hash+:
6722 * You can create a +Hash+ by calling method Hash.[].
6724 * Create an empty +Hash+:
6729 * Create a +Hash+ with initial entries:
6731 * h = Hash[foo: 0, bar: 1, baz: 2]
6732 * h # => {:foo=>0, :bar=>1, :baz=>2}
6734 * You can create a +Hash+ by using its literal form (curly braces).
6736 * Create an empty +Hash+:
6741 * Create a +Hash+ with initial entries:
6743 * h = {foo: 0, bar: 1, baz: 2}
6744 * h # => {:foo=>0, :bar=>1, :baz=>2}
6747 * === +Hash+ Value Basics
6749 * The simplest way to retrieve a +Hash+ value (instance method #[]):
6751 * h = {foo: 0, bar: 1, baz: 2}
6754 * The simplest way to create or update a +Hash+ value (instance method #[]=):
6756 * h = {foo: 0, bar: 1, baz: 2}
6757 * h[:bat] = 3 # => 3
6758 * h # => {:foo=>0, :bar=>1, :baz=>2, :bat=>3}
6759 * h[:foo] = 4 # => 4
6760 * h # => {:foo=>4, :bar=>1, :baz=>2, :bat=>3}
6762 * The simplest way to delete a +Hash+ entry (instance method #delete):
6764 * h = {foo: 0, bar: 1, baz: 2}
6765 * h.delete(:bar) # => 1
6766 * h # => {:foo=>0, :baz=>2}
6770 * A +Hash+ object presents its entries in the order of their creation. This is seen in:
6772 * - Iterative methods such as <tt>each</tt>, <tt>each_key</tt>, <tt>each_pair</tt>, <tt>each_value</tt>.
6773 * - Other order-sensitive methods such as <tt>shift</tt>, <tt>keys</tt>, <tt>values</tt>.
6774 * - The String returned by method <tt>inspect</tt>.
6776 * A new +Hash+ has its initial ordering per the given entries:
6778 * h = Hash[foo: 0, bar: 1]
6779 * h # => {:foo=>0, :bar=>1}
6781 * New entries are added at the end:
6784 * h # => {:foo=>0, :bar=>1, :baz=>2}
6786 * Updating a value does not affect the order:
6789 * h # => {:foo=>0, :bar=>1, :baz=>3}
6791 * But re-creating a deleted entry can affect the order:
6795 * h # => {:bar=>1, :baz=>3, :foo=>5}
6799 * ==== +Hash+ Key Equivalence
6801 * Two objects are treated as the same \hash key when their <code>hash</code> value
6802 * is identical and the two objects are <code>eql?</code> to each other.
6804 * ==== Modifying an Active +Hash+ Key
6806 * Modifying a +Hash+ key while it is in use damages the hash's index.
6808 * This +Hash+ has keys that are Arrays:
6810 * a0 = [ :foo, :bar ]
6811 * a1 = [ :baz, :bat ]
6812 * h = {a0 => 0, a1 => 1}
6813 * h.include?(a0) # => true
6815 * a0.hash # => 110002110
6817 * Modifying array element <tt>a0[0]</tt> changes its hash value:
6820 * a0.hash # => 1069447059
6822 * And damages the +Hash+ index:
6824 * h.include?(a0) # => false
6827 * You can repair the hash index using method +rehash+:
6829 * h.rehash # => {[:bam, :bar]=>0, [:baz, :bat]=>1}
6830 * h.include?(a0) # => true
6833 * A String key is always safe.
6834 * That's because an unfrozen String
6835 * passed as a key will be replaced by a duplicated and frozen String:
6838 * s.frozen? # => false
6840 * first_key = h.keys.first
6841 * first_key.frozen? # => true
6843 * ==== User-Defined +Hash+ Keys
6845 * To be useable as a +Hash+ key, objects must implement the methods <code>hash</code> and <code>eql?</code>.
6846 * Note: this requirement does not apply if the +Hash+ uses #compare_by_identity since comparison will then
6847 * rely on the keys' object id instead of <code>hash</code> and <code>eql?</code>.
6849 * Object defines basic implementation for <code>hash</code> and <code>eq?</code> that makes each object
6850 * a distinct key. Typically, user-defined classes will want to override these methods to provide meaningful
6851 * behavior, or for example inherit Struct that has useful definitions for these.
6853 * A typical implementation of <code>hash</code> is based on the
6854 * object's data while <code>eql?</code> is usually aliased to the overridden
6855 * <code>==</code> method:
6858 * attr_reader :author, :title
6860 * def initialize(author, title)
6866 * self.class === other &&
6867 * other.author == @author &&
6868 * other.title == @title
6874 * [self.class, @author, @title].hash
6878 * book1 = Book.new 'matz', 'Ruby in a Nutshell'
6879 * book2 = Book.new 'matz', 'Ruby in a Nutshell'
6883 * reviews[book1] = 'Great reference!'
6884 * reviews[book2] = 'Nice and compact!'
6886 * reviews.length #=> 1
6888 * === Default Values
6890 * The methods #[], #values_at and #dig need to return the value associated to a certain key.
6891 * When that key is not found, that value will be determined by its default proc (if any)
6892 * or else its default (initially `nil`).
6894 * You can retrieve the default value with method #default:
6897 * h.default # => nil
6899 * You can set the default value by passing an argument to method Hash.new or
6900 * with method #default=
6907 * This default value is returned for #[], #values_at and #dig when a key is
6910 * counts = {foo: 42}
6911 * counts.default # => nil (default)
6913 * counts[:bar] # => nil
6914 * counts.default = 0
6915 * counts[:bar] # => 0
6916 * counts.values_at(:foo, :bar, :baz) # => [42, 0, 0]
6917 * counts.dig(:bar) # => 0
6919 * Note that the default value is used without being duplicated. It is not advised to set
6920 * the default value to a mutable object:
6922 * synonyms = Hash.new([])
6923 * synonyms[:hello] # => []
6924 * synonyms[:hello] << :hi # => [:hi], but this mutates the default!
6925 * synonyms.default # => [:hi]
6926 * synonyms[:world] << :universe
6927 * synonyms[:world] # => [:hi, :universe], oops
6928 * synonyms.keys # => [], oops
6930 * To use a mutable object as default, it is recommended to use a default proc
6934 * When the default proc for a +Hash+ is set (i.e., not +nil+),
6935 * the default value returned by method #[] is determined by the default proc alone.
6937 * You can retrieve the default proc with method #default_proc:
6940 * h.default_proc # => nil
6942 * You can set the default proc by calling Hash.new with a block or
6943 * calling the method #default_proc=
6945 * h = Hash.new { |hash, key| "Default value for #{key}" }
6946 * h.default_proc.class # => Proc
6947 * h.default_proc = proc { |hash, key| "Default value for #{key.inspect}" }
6948 * h.default_proc.class # => Proc
6950 * When the default proc is set (i.e., not +nil+)
6951 * and method #[] is called with with a non-existent key,
6952 * #[] calls the default proc with both the +Hash+ object itself and the missing key,
6953 * then returns the proc's return value:
6955 * h = Hash.new { |hash, key| "Default value for #{key}" }
6956 * h[:nosuch] # => "Default value for nosuch"
6958 * Note that in the example above no entry for key +:nosuch+ is created:
6960 * h.include?(:nosuch) # => false
6962 * However, the proc itself can add a new entry:
6964 * synonyms = Hash.new { |hash, key| hash[key] = [] }
6965 * synonyms.include?(:hello) # => false
6966 * synonyms[:hello] << :hi # => [:hi]
6967 * synonyms[:world] << :universe # => [:universe]
6968 * synonyms.keys # => [:hello, :world]
6970 * Note that setting the default proc will clear the default value and vice versa.
6972 * Be aware that a default proc that modifies the hash is not thread-safe in the
6973 * sense that multiple threads can call into the default proc concurrently for the
6978 * First, what's elsewhere. \Class +Hash+:
6980 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
6981 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
6982 * which provides dozens of additional methods.
6984 * Here, class +Hash+ provides methods that are useful for:
6986 * - {Creating a Hash}[rdoc-ref:Hash@Methods+for+Creating+a+Hash]
6987 * - {Setting Hash State}[rdoc-ref:Hash@Methods+for+Setting+Hash+State]
6988 * - {Querying}[rdoc-ref:Hash@Methods+for+Querying]
6989 * - {Comparing}[rdoc-ref:Hash@Methods+for+Comparing]
6990 * - {Fetching}[rdoc-ref:Hash@Methods+for+Fetching]
6991 * - {Assigning}[rdoc-ref:Hash@Methods+for+Assigning]
6992 * - {Deleting}[rdoc-ref:Hash@Methods+for+Deleting]
6993 * - {Iterating}[rdoc-ref:Hash@Methods+for+Iterating]
6994 * - {Converting}[rdoc-ref:Hash@Methods+for+Converting]
6995 * - {Transforming Keys and Values}[rdoc-ref:Hash@Methods+for+Transforming+Keys+and+Values]
6996 * - {And more....}[rdoc-ref:Hash@Other+Methods]
6998 * \Class +Hash+ also includes methods from module Enumerable.
7000 * ==== Methods for Creating a +Hash+
7002 * - ::[]: Returns a new hash populated with given objects.
7003 * - ::new: Returns a new empty hash.
7004 * - ::try_convert: Returns a new hash created from a given object.
7006 * ==== Methods for Setting +Hash+ State
7008 * - #compare_by_identity: Sets +self+ to consider only identity in comparing keys.
7009 * - #default=: Sets the default to a given value.
7010 * - #default_proc=: Sets the default proc to a given proc.
7011 * - #rehash: Rebuilds the hash table by recomputing the hash index for each key.
7013 * ==== Methods for Querying
7015 * - #any?: Returns whether any element satisfies a given criterion.
7016 * - #compare_by_identity?: Returns whether the hash considers only identity when comparing keys.
7017 * - #default: Returns the default value, or the default value for a given key.
7018 * - #default_proc: Returns the default proc.
7019 * - #empty?: Returns whether there are no entries.
7020 * - #eql?: Returns whether a given object is equal to +self+.
7021 * - #hash: Returns the integer hash code.
7022 * - #has_value?: Returns whether a given object is a value in +self+.
7023 * - #include?, #has_key?, #member?, #key?: Returns whether a given object is a key in +self+.
7024 * - #length, #size: Returns the count of entries.
7025 * - #value?: Returns whether a given object is a value in +self+.
7027 * ==== Methods for Comparing
7029 * - #<: Returns whether +self+ is a proper subset of a given object.
7030 * - #<=: Returns whether +self+ is a subset of a given object.
7031 * - #==: Returns whether a given object is equal to +self+.
7032 * - #>: Returns whether +self+ is a proper superset of a given object
7033 * - #>=: Returns whether +self+ is a superset of a given object.
7035 * ==== Methods for Fetching
7037 * - #[]: Returns the value associated with a given key.
7038 * - #assoc: Returns a 2-element array containing a given key and its value.
7039 * - #dig: Returns the object in nested objects that is specified
7040 * by a given key and additional arguments.
7041 * - #fetch: Returns the value for a given key.
7042 * - #fetch_values: Returns array containing the values associated with given keys.
7043 * - #key: Returns the key for the first-found entry with a given value.
7044 * - #keys: Returns an array containing all keys in +self+.
7045 * - #rassoc: Returns a 2-element array consisting of the key and value
7046 * of the first-found entry having a given value.
7047 * - #values: Returns an array containing all values in +self+/
7048 * - #values_at: Returns an array containing values for given keys.
7050 * ==== Methods for Assigning
7052 * - #[]=, #store: Associates a given key with a given value.
7053 * - #merge: Returns the hash formed by merging each given hash into a copy of +self+.
7054 * - #merge!, #update: Merges each given hash into +self+.
7055 * - #replace: Replaces the entire contents of +self+ with the contents of a given hash.
7057 * ==== Methods for Deleting
7059 * These methods remove entries from +self+:
7061 * - #clear: Removes all entries from +self+.
7062 * - #compact!: Removes all +nil+-valued entries from +self+.
7063 * - #delete: Removes the entry for a given key.
7064 * - #delete_if: Removes entries selected by a given block.
7065 * - #filter!, #select!: Keep only those entries selected by a given block.
7066 * - #keep_if: Keep only those entries selected by a given block.
7067 * - #reject!: Removes entries selected by a given block.
7068 * - #shift: Removes and returns the first entry.
7070 * These methods return a copy of +self+ with some entries removed:
7072 * - #compact: Returns a copy of +self+ with all +nil+-valued entries removed.
7073 * - #except: Returns a copy of +self+ with entries removed for specified keys.
7074 * - #filter, #select: Returns a copy of +self+ with only those entries selected by a given block.
7075 * - #reject: Returns a copy of +self+ with entries removed as specified by a given block.
7076 * - #slice: Returns a hash containing the entries for given keys.
7078 * ==== Methods for Iterating
7079 * - #each, #each_pair: Calls a given block with each key-value pair.
7080 * - #each_key: Calls a given block with each key.
7081 * - #each_value: Calls a given block with each value.
7083 * ==== Methods for Converting
7085 * - #inspect, #to_s: Returns a new String containing the hash entries.
7086 * - #to_a: Returns a new array of 2-element arrays;
7087 * each nested array contains a key-value pair from +self+.
7088 * - #to_h: Returns +self+ if a +Hash+;
7089 * if a subclass of +Hash+, returns a +Hash+ containing the entries from +self+.
7090 * - #to_hash: Returns +self+.
7091 * - #to_proc: Returns a proc that maps a given key to its value.
7093 * ==== Methods for Transforming Keys and Values
7095 * - #transform_keys: Returns a copy of +self+ with modified keys.
7096 * - #transform_keys!: Modifies keys in +self+
7097 * - #transform_values: Returns a copy of +self+ with modified values.
7098 * - #transform_values!: Modifies values in +self+.
7100 * ==== Other Methods
7101 * - #flatten: Returns an array that is a 1-dimensional flattening of +self+.
7102 * - #invert: Returns a hash with the each key-value pair inverted.
7109 id_hash
= rb_intern_const("hash");
7110 id_flatten_bang
= rb_intern_const("flatten!");
7111 id_hash_iter_lev
= rb_make_internal_id();
7113 rb_cHash
= rb_define_class("Hash", rb_cObject
);
7115 rb_include_module(rb_cHash
, rb_mEnumerable
);
7117 rb_define_alloc_func(rb_cHash
, empty_hash_alloc
);
7118 rb_define_singleton_method(rb_cHash
, "[]", rb_hash_s_create
, -1);
7119 rb_define_singleton_method(rb_cHash
, "try_convert", rb_hash_s_try_convert
, 1);
7120 rb_define_method(rb_cHash
, "initialize_copy", rb_hash_replace
, 1);
7121 rb_define_method(rb_cHash
, "rehash", rb_hash_rehash
, 0);
7123 rb_define_method(rb_cHash
, "to_hash", rb_hash_to_hash
, 0);
7124 rb_define_method(rb_cHash
, "to_h", rb_hash_to_h
, 0);
7125 rb_define_method(rb_cHash
, "to_a", rb_hash_to_a
, 0);
7126 rb_define_method(rb_cHash
, "inspect", rb_hash_inspect
, 0);
7127 rb_define_alias(rb_cHash
, "to_s", "inspect");
7128 rb_define_method(rb_cHash
, "to_proc", rb_hash_to_proc
, 0);
7130 rb_define_method(rb_cHash
, "==", rb_hash_equal
, 1);
7131 rb_define_method(rb_cHash
, "[]", rb_hash_aref
, 1);
7132 rb_define_method(rb_cHash
, "hash", rb_hash_hash
, 0);
7133 rb_define_method(rb_cHash
, "eql?", rb_hash_eql
, 1);
7134 rb_define_method(rb_cHash
, "fetch", rb_hash_fetch_m
, -1);
7135 rb_define_method(rb_cHash
, "[]=", rb_hash_aset
, 2);
7136 rb_define_method(rb_cHash
, "store", rb_hash_aset
, 2);
7137 rb_define_method(rb_cHash
, "default", rb_hash_default
, -1);
7138 rb_define_method(rb_cHash
, "default=", rb_hash_set_default
, 1);
7139 rb_define_method(rb_cHash
, "default_proc", rb_hash_default_proc
, 0);
7140 rb_define_method(rb_cHash
, "default_proc=", rb_hash_set_default_proc
, 1);
7141 rb_define_method(rb_cHash
, "key", rb_hash_key
, 1);
7142 rb_define_method(rb_cHash
, "size", rb_hash_size
, 0);
7143 rb_define_method(rb_cHash
, "length", rb_hash_size
, 0);
7144 rb_define_method(rb_cHash
, "empty?", rb_hash_empty_p
, 0);
7146 rb_define_method(rb_cHash
, "each_value", rb_hash_each_value
, 0);
7147 rb_define_method(rb_cHash
, "each_key", rb_hash_each_key
, 0);
7148 rb_define_method(rb_cHash
, "each_pair", rb_hash_each_pair
, 0);
7149 rb_define_method(rb_cHash
, "each", rb_hash_each_pair
, 0);
7151 rb_define_method(rb_cHash
, "transform_keys", rb_hash_transform_keys
, -1);
7152 rb_define_method(rb_cHash
, "transform_keys!", rb_hash_transform_keys_bang
, -1);
7153 rb_define_method(rb_cHash
, "transform_values", rb_hash_transform_values
, 0);
7154 rb_define_method(rb_cHash
, "transform_values!", rb_hash_transform_values_bang
, 0);
7156 rb_define_method(rb_cHash
, "keys", rb_hash_keys
, 0);
7157 rb_define_method(rb_cHash
, "values", rb_hash_values
, 0);
7158 rb_define_method(rb_cHash
, "values_at", rb_hash_values_at
, -1);
7159 rb_define_method(rb_cHash
, "fetch_values", rb_hash_fetch_values
, -1);
7161 rb_define_method(rb_cHash
, "shift", rb_hash_shift
, 0);
7162 rb_define_method(rb_cHash
, "delete", rb_hash_delete_m
, 1);
7163 rb_define_method(rb_cHash
, "delete_if", rb_hash_delete_if
, 0);
7164 rb_define_method(rb_cHash
, "keep_if", rb_hash_keep_if
, 0);
7165 rb_define_method(rb_cHash
, "select", rb_hash_select
, 0);
7166 rb_define_method(rb_cHash
, "select!", rb_hash_select_bang
, 0);
7167 rb_define_method(rb_cHash
, "filter", rb_hash_select
, 0);
7168 rb_define_method(rb_cHash
, "filter!", rb_hash_select_bang
, 0);
7169 rb_define_method(rb_cHash
, "reject", rb_hash_reject
, 0);
7170 rb_define_method(rb_cHash
, "reject!", rb_hash_reject_bang
, 0);
7171 rb_define_method(rb_cHash
, "slice", rb_hash_slice
, -1);
7172 rb_define_method(rb_cHash
, "except", rb_hash_except
, -1);
7173 rb_define_method(rb_cHash
, "clear", rb_hash_clear
, 0);
7174 rb_define_method(rb_cHash
, "invert", rb_hash_invert
, 0);
7175 rb_define_method(rb_cHash
, "update", rb_hash_update
, -1);
7176 rb_define_method(rb_cHash
, "replace", rb_hash_replace
, 1);
7177 rb_define_method(rb_cHash
, "merge!", rb_hash_update
, -1);
7178 rb_define_method(rb_cHash
, "merge", rb_hash_merge
, -1);
7179 rb_define_method(rb_cHash
, "assoc", rb_hash_assoc
, 1);
7180 rb_define_method(rb_cHash
, "rassoc", rb_hash_rassoc
, 1);
7181 rb_define_method(rb_cHash
, "flatten", rb_hash_flatten
, -1);
7182 rb_define_method(rb_cHash
, "compact", rb_hash_compact
, 0);
7183 rb_define_method(rb_cHash
, "compact!", rb_hash_compact_bang
, 0);
7185 rb_define_method(rb_cHash
, "include?", rb_hash_has_key
, 1);
7186 rb_define_method(rb_cHash
, "member?", rb_hash_has_key
, 1);
7187 rb_define_method(rb_cHash
, "has_key?", rb_hash_has_key
, 1);
7188 rb_define_method(rb_cHash
, "has_value?", rb_hash_has_value
, 1);
7189 rb_define_method(rb_cHash
, "key?", rb_hash_has_key
, 1);
7190 rb_define_method(rb_cHash
, "value?", rb_hash_has_value
, 1);
7192 rb_define_method(rb_cHash
, "compare_by_identity", rb_hash_compare_by_id
, 0);
7193 rb_define_method(rb_cHash
, "compare_by_identity?", rb_hash_compare_by_id_p
, 0);
7195 rb_define_method(rb_cHash
, "any?", rb_hash_any_p
, -1);
7196 rb_define_method(rb_cHash
, "dig", rb_hash_dig
, -1);
7198 rb_define_method(rb_cHash
, "<=", rb_hash_le
, 1);
7199 rb_define_method(rb_cHash
, "<", rb_hash_lt
, 1);
7200 rb_define_method(rb_cHash
, ">=", rb_hash_ge
, 1);
7201 rb_define_method(rb_cHash
, ">", rb_hash_gt
, 1);
7203 rb_define_method(rb_cHash
, "deconstruct_keys", rb_hash_deconstruct_keys
, 1);
7205 rb_define_singleton_method(rb_cHash
, "ruby2_keywords_hash?", rb_hash_s_ruby2_keywords_hash_p
, 1);
7206 rb_define_singleton_method(rb_cHash
, "ruby2_keywords_hash", rb_hash_s_ruby2_keywords_hash
, 1);
7208 /* Document-class: ENV
7210 * +ENV+ is a hash-like accessor for environment variables.
7212 * === Interaction with the Operating System
7214 * The +ENV+ object interacts with the operating system's environment variables:
7216 * - When you get the value for a name in +ENV+, the value is retrieved from among the current environment variables.
7217 * - When you create or set a name-value pair in +ENV+, the name and value are immediately set in the environment variables.
7218 * - When you delete a name-value pair in +ENV+, it is immediately deleted from the environment variables.
7220 * === Names and Values
7222 * Generally, a name or value is a String.
7224 * ==== Valid Names and Values
7226 * Each name or value must be one of the following:
7229 * - An object that responds to \#to_str by returning a String, in which case that String will be used as the name or value.
7231 * ==== Invalid Names and Values
7235 * - May not be the empty string:
7237 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv())
7239 * - May not contain character <code>"="</code>:
7241 * # Raises Errno::EINVAL (Invalid argument - ruby_setenv(=))
7243 * A new name or value:
7245 * - May not be a non-String that does not respond to \#to_str:
7247 * ENV['foo'] = Object.new
7248 * # Raises TypeError (no implicit conversion of Object into String)
7249 * ENV[Object.new] = '0'
7250 * # Raises TypeError (no implicit conversion of Object into String)
7252 * - May not contain the NUL character <code>"\0"</code>:
7255 * # Raises ArgumentError (bad environment variable value: contains null byte)
7257 * # Raises ArgumentError (bad environment variable name: contains null byte)
7259 * - May not have an ASCII-incompatible encoding such as UTF-16LE or ISO-2022-JP:
7261 * ENV['foo'] = '0'.force_encoding(Encoding::ISO_2022_JP)
7262 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7263 * ENV["foo".force_encoding(Encoding::ISO_2022_JP)] = '0'
7264 * # Raises ArgumentError (bad environment variable name: ASCII incompatible encoding: ISO-2022-JP)
7266 * === About Ordering
7268 * +ENV+ enumerates its name/value pairs in the order found
7269 * in the operating system's environment variables.
7270 * Therefore the ordering of +ENV+ content is OS-dependent, and may be indeterminate.
7272 * This will be seen in:
7273 * - A Hash returned by an +ENV+ method.
7274 * - An Enumerator returned by an +ENV+ method.
7275 * - An Array returned by ENV.keys, ENV.values, or ENV.to_a.
7276 * - The String returned by ENV.inspect.
7277 * - The Array returned by ENV.shift.
7278 * - The name returned by ENV.key.
7280 * === About the Examples
7281 * Some methods in +ENV+ return +ENV+ itself. Typically, there are many environment variables.
7282 * It's not useful to display a large +ENV+ in the examples here,
7283 * so most example snippets begin by resetting the contents of +ENV+:
7284 * - ENV.replace replaces +ENV+ with a new collection of entries.
7285 * - ENV.clear empties +ENV+.
7289 * First, what's elsewhere. \Class +ENV+:
7291 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
7292 * - Extends {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
7294 * Here, class +ENV+ provides methods that are useful for:
7296 * - {Querying}[rdoc-ref:ENV@Methods+for+Querying]
7297 * - {Assigning}[rdoc-ref:ENV@Methods+for+Assigning]
7298 * - {Deleting}[rdoc-ref:ENV@Methods+for+Deleting]
7299 * - {Iterating}[rdoc-ref:ENV@Methods+for+Iterating]
7300 * - {Converting}[rdoc-ref:ENV@Methods+for+Converting]
7301 * - {And more ....}[rdoc-ref:ENV@More+Methods]
7303 * ==== Methods for Querying
7305 * - ::[]: Returns the value for the given environment variable name if it exists:
7306 * - ::empty?: Returns whether +ENV+ is empty.
7307 * - ::has_value?, ::value?: Returns whether the given value is in +ENV+.
7308 * - ::include?, ::has_key?, ::key?, ::member?: Returns whether the given name
7310 * - ::key: Returns the name of the first entry with the given value.
7311 * - ::size, ::length: Returns the number of entries.
7312 * - ::value?: Returns whether any entry has the given value.
7314 * ==== Methods for Assigning
7316 * - ::[]=, ::store: Creates, updates, or deletes the named environment variable.
7317 * - ::clear: Removes every environment variable; returns +ENV+:
7318 * - ::update, ::merge!: Adds to +ENV+ each key/value pair in the given hash.
7319 * - ::replace: Replaces the entire content of the +ENV+
7320 * with the name/value pairs in the given hash.
7322 * ==== Methods for Deleting
7324 * - ::delete: Deletes the named environment variable name if it exists.
7325 * - ::delete_if: Deletes entries selected by the block.
7326 * - ::keep_if: Deletes entries not selected by the block.
7327 * - ::reject!: Similar to #delete_if, but returns +nil+ if no change was made.
7328 * - ::select!, ::filter!: Deletes entries selected by the block.
7329 * - ::shift: Removes and returns the first entry.
7331 * ==== Methods for Iterating
7333 * - ::each, ::each_pair: Calls the block with each name/value pair.
7334 * - ::each_key: Calls the block with each name.
7335 * - ::each_value: Calls the block with each value.
7337 * ==== Methods for Converting
7339 * - ::assoc: Returns a 2-element array containing the name and value
7340 * of the named environment variable if it exists:
7341 * - ::clone: Returns +ENV+ (and issues a warning).
7342 * - ::except: Returns a hash of all name/value pairs except those given.
7343 * - ::fetch: Returns the value for the given name.
7344 * - ::inspect: Returns the contents of +ENV+ as a string.
7345 * - ::invert: Returns a hash whose keys are the +ENV+ values,
7346 and whose values are the corresponding +ENV+ names.
7347 * - ::keys: Returns an array of all names.
7348 * - ::rassoc: Returns the name and value of the first found entry
7349 * that has the given value.
7350 * - ::reject: Returns a hash of those entries not rejected by the block.
7351 * - ::select, ::filter: Returns a hash of name/value pairs selected by the block.
7352 * - ::slice: Returns a hash of the given names and their corresponding values.
7353 * - ::to_a: Returns the entries as an array of 2-element Arrays.
7354 * - ::to_h: Returns a hash of entries selected by the block.
7355 * - ::to_hash: Returns a hash of all entries.
7356 * - ::to_s: Returns the string <tt>'ENV'</tt>.
7357 * - ::values: Returns all values as an array.
7358 * - ::values_at: Returns an array of the values for the given name.
7362 * - ::dup: Raises an exception.
7363 * - ::freeze: Raises an exception.
7364 * - ::rehash: Returns +nil+, without modifying +ENV+.
7369 * Hack to get RDoc to regard ENV as a class:
7370 * envtbl = rb_define_class("ENV", rb_cObject);
7372 origenviron
= environ
;
7373 envtbl
= TypedData_Wrap_Struct(rb_cObject
, &env_data_type
, NULL
);
7374 rb_extend_object(envtbl
, rb_mEnumerable
);
7375 FL_SET_RAW(envtbl
, RUBY_FL_SHAREABLE
);
7378 rb_define_singleton_method(envtbl
, "[]", rb_f_getenv
, 1);
7379 rb_define_singleton_method(envtbl
, "fetch", env_fetch
, -1);
7380 rb_define_singleton_method(envtbl
, "[]=", env_aset_m
, 2);
7381 rb_define_singleton_method(envtbl
, "store", env_aset_m
, 2);
7382 rb_define_singleton_method(envtbl
, "each", env_each_pair
, 0);
7383 rb_define_singleton_method(envtbl
, "each_pair", env_each_pair
, 0);
7384 rb_define_singleton_method(envtbl
, "each_key", env_each_key
, 0);
7385 rb_define_singleton_method(envtbl
, "each_value", env_each_value
, 0);
7386 rb_define_singleton_method(envtbl
, "delete", env_delete_m
, 1);
7387 rb_define_singleton_method(envtbl
, "delete_if", env_delete_if
, 0);
7388 rb_define_singleton_method(envtbl
, "keep_if", env_keep_if
, 0);
7389 rb_define_singleton_method(envtbl
, "slice", env_slice
, -1);
7390 rb_define_singleton_method(envtbl
, "except", env_except
, -1);
7391 rb_define_singleton_method(envtbl
, "clear", env_clear
, 0);
7392 rb_define_singleton_method(envtbl
, "reject", env_reject
, 0);
7393 rb_define_singleton_method(envtbl
, "reject!", env_reject_bang
, 0);
7394 rb_define_singleton_method(envtbl
, "select", env_select
, 0);
7395 rb_define_singleton_method(envtbl
, "select!", env_select_bang
, 0);
7396 rb_define_singleton_method(envtbl
, "filter", env_select
, 0);
7397 rb_define_singleton_method(envtbl
, "filter!", env_select_bang
, 0);
7398 rb_define_singleton_method(envtbl
, "shift", env_shift
, 0);
7399 rb_define_singleton_method(envtbl
, "freeze", env_freeze
, 0);
7400 rb_define_singleton_method(envtbl
, "invert", env_invert
, 0);
7401 rb_define_singleton_method(envtbl
, "replace", env_replace
, 1);
7402 rb_define_singleton_method(envtbl
, "update", env_update
, -1);
7403 rb_define_singleton_method(envtbl
, "merge!", env_update
, -1);
7404 rb_define_singleton_method(envtbl
, "inspect", env_inspect
, 0);
7405 rb_define_singleton_method(envtbl
, "rehash", env_none
, 0);
7406 rb_define_singleton_method(envtbl
, "to_a", env_to_a
, 0);
7407 rb_define_singleton_method(envtbl
, "to_s", env_to_s
, 0);
7408 rb_define_singleton_method(envtbl
, "key", env_key
, 1);
7409 rb_define_singleton_method(envtbl
, "size", env_size
, 0);
7410 rb_define_singleton_method(envtbl
, "length", env_size
, 0);
7411 rb_define_singleton_method(envtbl
, "empty?", env_empty_p
, 0);
7412 rb_define_singleton_method(envtbl
, "keys", env_f_keys
, 0);
7413 rb_define_singleton_method(envtbl
, "values", env_f_values
, 0);
7414 rb_define_singleton_method(envtbl
, "values_at", env_values_at
, -1);
7415 rb_define_singleton_method(envtbl
, "include?", env_has_key
, 1);
7416 rb_define_singleton_method(envtbl
, "member?", env_has_key
, 1);
7417 rb_define_singleton_method(envtbl
, "has_key?", env_has_key
, 1);
7418 rb_define_singleton_method(envtbl
, "has_value?", env_has_value
, 1);
7419 rb_define_singleton_method(envtbl
, "key?", env_has_key
, 1);
7420 rb_define_singleton_method(envtbl
, "value?", env_has_value
, 1);
7421 rb_define_singleton_method(envtbl
, "to_hash", env_f_to_hash
, 0);
7422 rb_define_singleton_method(envtbl
, "to_h", env_to_h
, 0);
7423 rb_define_singleton_method(envtbl
, "assoc", env_assoc
, 1);
7424 rb_define_singleton_method(envtbl
, "rassoc", env_rassoc
, 1);
7425 rb_define_singleton_method(envtbl
, "clone", env_clone
, -1);
7426 rb_define_singleton_method(envtbl
, "dup", env_dup
, 0);
7428 VALUE envtbl_class
= rb_singleton_class(envtbl
);
7429 rb_undef_method(envtbl_class
, "initialize");
7430 rb_undef_method(envtbl_class
, "initialize_clone");
7431 rb_undef_method(envtbl_class
, "initialize_copy");
7432 rb_undef_method(envtbl_class
, "initialize_dup");
7435 * +ENV+ is a Hash-like accessor for environment variables.
7437 * See ENV (the class) for more details.
7439 rb_define_global_const("ENV", envtbl
);
7441 HASH_ASSERT(sizeof(ar_hint_t
) * RHASH_AR_TABLE_MAX_SIZE
== sizeof(VALUE
));
7444 #include "hash.rbinc"