instance method
Hash#shift
() -> [ K, V ]?
shift → [key, value] or nil
hash.c
View on GitHub ↗
static VALUE
rb_hash_shift(VALUE hash)
{
struct shift_var var;
rb_hash_modify_check(hash);
if (RHASH_AR_TABLE_P(hash)) {
var.key = Qundef;
if (!hash_iterating_p(hash)) {
if (ar_shift(hash, &var.key, &var.val)) {
return rb_assoc_new(var.key, var.val);
}
}
else {
rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
if (!UNDEF_P(var.key)) {
rb_hash_delete_entry(hash, var.key);
return rb_assoc_new(var.key, var.val);
}
}
}
if (RHASH_ST_TABLE_P(hash)) {
var.key = Qundef;
if (!hash_iterating_p(hash)) {
if (st_shift(RHASH_ST_TABLE(hash), &var.key, &var.val)) {
return rb_assoc_new(var.key, var.val);
}
}
else {
rb_hash_foreach(hash, shift_i_safe, (VALUE)&var);
if (!UNDEF_P(var.key)) {
rb_hash_delete_entry(hash, var.key);
return rb_assoc_new(var.key, var.val);
}
}
}
return Qnil;
}
Removes and returns the first entry of self as a 2-element array; see Entry Order:
Example
h = {foo: 0, bar: 1, baz: 2} h.shift # => [:foo, 0] h # => {bar: 1, baz: 2}
Returns nil if self is empty.
Related: see Methods for Deleting.
Ruby version changes
-
3.2
-
Hash#shiftnow always returns nil if the hash is empty, instead of returning the default value or calling the default proc. [Bug #16908]
-