Method: Hash#each

Defined in:
hash.c

#each {|key, value| ... } ⇒ self #each_pair {|key, value| ... } ⇒ self #eachObject #each_pairObject

Calls the given block with each key-value pair; returns self:

h = {foo: 0, bar: 1, baz: 2}
h.each_pair {|key, value| puts "#{key}: #{value}"} # => {:foo=>0, :bar=>1, :baz=>2}

Output:

foo: 0
bar: 1
baz: 2

Returns a new Enumerator if no block given:

h = {foo: 0, bar: 1, baz: 2}
e = h.each_pair # => #<Enumerator: {:foo=>0, :bar=>1, :baz=>2}:each_pair>
h1 = e.each {|key, value| puts "#{key}: #{value}"}
h1 # => {:foo=>0, :bar=>1, :baz=>2}

Output:

foo: 0
bar: 1
baz: 2

Overloads:

  • #each {|key, value| ... } ⇒ self

    Yields:

    Returns:

    • (self)
  • #each_pair {|key, value| ... } ⇒ self

    Yields:

    Returns:

    • (self)


3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
# File 'hash.c', line 3132

static VALUE
rb_hash_each_pair(VALUE hash)
{
    RETURN_SIZED_ENUMERATOR(hash, 0, 0, hash_enum_size);
    if (rb_block_pair_yield_optimizable())
        rb_hash_foreach(hash, each_pair_i_fast, 0);
    else
        rb_hash_foreach(hash, each_pair_i, 0);
    return hash;
}